[R] Create a variable lenght string that can be used in a dimnames statement
Ivan Krylov
kry|ov@r00t @end|ng |rom gm@||@com
Tue Jul 4 09:14:43 CEST 2023
On Mon, 3 Jul 2023 20:08:06 +0000
"Sorkin, John" <jsorkin using som.umaryland.edu> wrote:
> # create variable names xxx1 and xxx2.
> string=""
> for (j in 1:2){
> name <- paste("xxx",j,sep="")
> string <- paste(string,name)
> print(string)
> }
> # Creation of xxx1 and xxx2 works
> string
You need to distinguish between a space separated string and a string
vector. A space separated string is a single object that R won't split
for you unless you tell it to. (Are you coming from a Unix background?
A command line shell will split a space-separated string into a list of
words unless you tell it not to do that, but that's because its main
job is to convert space separated command lines typed by the operator
into lists of command line arguments. R is not like that at all.)
What you're getting here is an individual string. You can confirm that
by typing:
string[1]
and still seeing the whole string. You can also type:
string[2]
and see an NA instead of the second word in the string.
Try replacing the _second_ paste() in the example above with a c().
Given individual strings, paste() concatenates its arguments into
a string. c() concatenates its arguments into a vector of separate
objects. You should still get a variable named `string`, but when you
print it whole, the results will look different (R will separate the
two strings inside that vector), and you should be able to type
string[1] and string[2] and get "xxx1" and "xxx2" respectively.
What about Rui's solution, the one that used paste() and got a vector,
contrary to what I wrote above? Rui gave a vector to paste(). paste()
runs a loop inside it and produces a string for every vector element of
it encounters, unless you tell it to collapse the result.
> zzz <- paste("j","k",string)
Same thing here. paste() adds spaces and returns a string. You need c()
to retain "j" and "k" separate from "xxx1" and "xxx2" as individual
elements of the vector.
It may *look* similar ([1] "j k xxx1 xxx2" vs. [1] "j" "k" "xxx1"
"xxx2"), but the resulting objects are different. When in doubt, use
str() on an object to see its structure.
--
Best regards,
Ivan
More information about the R-help
mailing list