Is is possible to access the current window width (in terms of characters) in an interactive session?
Say that we have a long string
x <- paste0(c(rep(letters, 10)), collapse = "")
One can use stringr to truncate the string and view it. For example:
stringr::str_trunc(x, 50)
results in
[1] "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstu..."
Would it be possible to make the truncating width variable so that the printed string is as large as possible while fitting in a single line?
Related
Using RDCOMClient, we can directly replace values in Excel cells, e.g.
range <- sheet$Range('A1')
range[['Value']] <- 1.2
In Word, Texts can be retrieved from the Text property of a range object, e.g.
word.doc[['Tables']][[1]]$Cell(2, 2)[['Range']][['Text']]
# "12/28/2022\r\a"
But while the Documentation of the range object says that the Text property can be used to retrieve or set the text of the range, this does not work in RDCOMClient:
word.doc[['Tables']][[1]]$Cell(2, 2)[['Range']][['Text']] <- "test"
# Error in word.doc[["Tables"]][[1]]$Cell(2, 2)[["Range"]][["Text"]] <- "test" :
target of assignment expands to non-language object
Is there a better way to edit the content of a cell or any other range/selection in Word?
If there is no way to do that, would selecting and Selection()$TypeText() or SearchReplace in the Range be more advisable?
It should work when you first get the Range object (from Word's viewpoint) and then set its Text property, e. g.:
library("RDCOMClient")
app <- COMCreate("Word.Application")
doc <- app$Documents()$Open('path_to_your_file.docx'))
## get the VBA object first:
the_range <- doc[['Tables']][[1]]$Cell(2, 2)[['Range']]
## assign its Text property:
the_range[['Text']] = "No cell is an island\n
Entire of itself;\n
Every cell needs a piece of content,\n
A part of the main."
doc$Save()
This is the command I'm using :
dallData <- fread("data.csv", showProgress = TRUE, colClasses = c(rep("NULL", 2), "character", rep("NULL", 37)))
but I get this error when trying to load it: R character strings are limited to 2^31-1 bytes|
Anyway to skip those values ?
Here's a strategy that may work or at least narrow down the possible sources of error. It assumes you have enough working memory to hold the data and that your separators are really commas. If you actually have tabs as separators then you will need to modify accordingly. The plan is to read using readLines which will basically ignore the quotes that are probably mismatched. Then figure out which line or lines are at fault using count.fields, table, and which.
input <- readLines("data.csv") # ignores quotes
counts.def <- count.fields(textConnection(input),
sep=",") # defaults quotes are both ' and "
table(counts.def) # might show a variety of line counts.
# Second try with just double-quotes
counts.dbl <- count.fields(textConnection(input),
sep=",", quote="\"") # just dbl-quotes
table(counts.dbl) # if all the same, then all you do is change the quotes argument
Depending on the results you may need to edit cerain lines which can be identified using which(counts.def < 40) assuming most of them are 40 as your input efforts suggest is the expected number of fields per line.
(If the tag for [ram] means you are limited and getting warnings or using virtual memory which slows things down horribly, then you should restart your OS, and only load R before trying again. R needs contiguous block of memory and Windoze isn't very good at memory management.)
Here's a small test case to work with:
input <- readLines(textConnection(
"v1,v2,v3,v4,v5,v6
text, text, text, text, text, text
text, text, O'Malley, text,text,text
junk,junk, more junk, \"text\", tex\"t, nothing
3,4,5,6,7,8")
I'm building a GUI using R and gWidgets (primarily with RGtk2 toolkit). This GUI will display in some places labels based on a (data-defined) string. This string can be arbitrarily long, but if it is too long it will break the GUI because it will force the widget to enlarge, therefore enlarging all the parents.
So, I need to trim the string to a length based on the space available for the label. I can see two solutions:
Force the glabel to have a max size = the size of its parent; this does not appear to be doable, but I'm happy to be corrected here;
determine the length of the string and, if it is too long, clip it before rendering. This seems easier, probably using low level pango functions, but I can not find out how to use them.
Pseudocode:
interface <- gwindow()
text <- "A Very very long label just to see what happens if you try to deliberately break the identification panel with stupidly long strings"
box <- gvbox(cont = interface)
lab <- glabel(text = text, cont = box)
Idea 1:
lab <- glabel(text = text, cont = box,maxsize = size(box))
Idea 2:
strLength <- strwidth(text, font = ???)
if strLength > size(box)[1] {
# Do something about it...
}
Here my problem is the syntax of font=. How can I read the definition of the font currently used by the widget, and convert it to R-friendly font syntax? Or is there perhaps a better way (low level pango function?) to get the string size?
I am trying to create a function that will calculate the frequency count of keywords using TM package. The function works fine if the text pasted from readline is on free form text without a new line. The problem is, when I paste a bunch of text copied from a spreadsheet, readline considers it as a new line.
keyword <- function() {
x <- readline(as.character('Input text here: '))
x <- Corpus(VectorSource(x))
...
tdm <- TermDocumentMatrix(x)
...
tdm
}
Here's the full code: https://github.com/CSCDataAnalytics/PM-Analysis/blob/master/Keyword.R
How can I prevent this from happening or at least consider a bunch of text of every row from the spreadsheet as one vector only?
If I'm understanding you correctly, the problem is when the user pastes the text from another application: the newline is causing R to stop accepting the subsequent lines.
One technique (fragile as it may be) is to look for a specific line, such as an empty line "" or a period ".". It's a little fragile because now you need (1) assurance that the data will "never" include that as a whole line, and (2) it is easily appended by the user.
Try:
endofinput <- ""
totalstr <- ""
while(! endofinput == (x <- readline('prompt (empty string when done): ')))
totalstr <- paste(totalstr, x)
In this case, the empty string is the catch, and when the while loop is done, totalstr contains all input separated by a space (this can be changed in the paste function).
NB: one problem with this technique is that it is "growing" the vector totalstr, which will eventually cause performance penalties (depending on the size of the input data): every loop iteration, more memory is allocated and the entire string is copied plus the new line of text. There are more verbose ways to side-step this problem (e.g., pre-allocate a vector larger than your anticipated input data), but if you aren't anticipated 1000s of lines then you may be able to accept this naive programming for simplicity.
Another option would be to have the user save the data to a text file and use file.choose() and readLines() to get your data.
Try collapsing the data into a single string after using readline
x <- paste(readline(as.character('Input text here: ')), collapse=' ')
I've been trying to create a table with a header that contains a like break. I am not too ambitious here and do not really care whether I just break extremely long strings or just have a two-line header in general.
dat <- matrix(round(rnorm(9, 20, 10)), 3, 3)
colnames(dat) <- c("some very long colname","short","another toooooooolong colname")
require(xtable)
m <- xtable(dat)
print(m,
floating=FALSE,
hline.after=NULL,
size="\\footnotesize",
tabular.environment="tabular",
add.to.row=list(pos=list(-1,0,nrow(m),0
),
command=c('\\toprule ',
'\\midrule ',
'\\bottomrule',
'\\\\ \\rowcolor[gray]{.9}'
)
)
)
Is there a way to line break the header, because my table is not fitting on the page anymore, though I use landscape already. Some sanitize.rownames based trick? Fiddled around with \shortstack but could not get it to go...
(Writing my comment up into a proper answer)
In the call to xtable, you can specify various alignment arguments, one of which is a parbox of a fixed width in which text will be wrapped. That is specified with p{1in} where the value specified within the braces is how wide the box (column) will be. You have to manually specify this (rather than have it adapt to the available space), but it does give you one option for wrapping text.