Reputation: 23
I have created a character vector using paste, for example:
y <- paste("a=1,b=2,c=3")
If I try to combine it:
x <- c(y)
I get:
[1] "a=1,b=2,c=3"
I would like to get the same as if I did:
c(a=1,b=2,c=3)
which gives:
a b c
1 2 3
Sorry if this is too basic, I am new to R (and the site). Thanks!
Upvotes: 1
Views: 334
Reputation: 263301
I wonder if this is what your really want, but since you asked, here it is. This is not considered good practice, but perhaps you have a use case that would make it useful.
> eval( parse(text=paste("c(", y, ")" ) ) )
a b c
1 2 3
The answedr fron Nader hints at what appears to be a missunderstanding about constructing R character variables. The paste
functions seems entirely superfluous for building y
: Just doing this is equivalent:
y <- "a=1,b=2,c=3"
Upvotes: 0
Reputation: 5414
y <- c("a=1,b=2,c=3")
list <- lapply(strsplit(y , ","), function(x){
strsplit(x , "=")
})
rapply(list, function(x){
setNames(x[2] , x[1])
})
# a b c
#"1" "2" "3"
Upvotes: 0
Reputation: 5152
Is not clear what you want, but one option:
sepstr<-function(list,sep=",")unlist(strsplit(list, sep, fixed = TRUE))
d=sapply(sepstr(y),sepstr, sep="=")
x=as.numeric(d[2,])
names(x)=d[1,]
x
Or as @thelatemail suggested:
x2=setNames(as.numeric(d[2,]),d[1,])
x2
Upvotes: 2