Reputation: 1114
New to R. I am trying to create a vector from each row in a dataframe, and name the vector after the position in the dataframe. Sample data:
a <- read.table(text='keyword1 keyword2
1 "hello" "goodbye"
2 "foo" "y"', header=TRUE)
each row should become a character string like:
name1 <- c("hello", "goodbye")
name2 <- c("foo", "y")
I'm thinking something like this, but its not quite there:
for (i in 1:length(a)) {
name <- a[i,1];
names <- c(name, a[i,2]);
Any help would be appreciated!
Upvotes: 1
Views: 559
Reputation: 99331
Here's another option
foo <- function(i) sapply(unname(a), as.character)[i,]
list2env(
setNames(Map(foo, 1:nrow(a)), gsub("keyword", "name", names(a))),
.GlobalEnv
)
name1
# [1] "hello" "goodbye"
name2
# [1] "foo" "y"
Upvotes: 1
Reputation: 61154
Here's one approach:
> rows <- sapply(1:2, function(i) strsplit(paste(a[i,1], a[i,2]), " "))
> names(rows) <- c("name1", "name2")
> list2env(rows, envir = .GlobalEnv)
# let's see the output:
> name1
[1] "hello" "goodbye"
> name2
[1] "foo" "y"
Upvotes: 2