I m trying to create a variable containing the value that people have assigned to different words. I created the following sample date to illustrate the issue.
words[1:3] are character vectors containing words, some appear several times, others only once.
value[1:3] are numeric vectors containing a number between 0 and 2.
allwords is a separate vector containing all words appearing in words[1:3].
data <- data.frame(
words1 <- c("apple", "pear", "banana", "pear", "banana"),
words2 <- c("pear", "banana", "pear", "banana", "cherry"),
words3 <- c("banana", "ananas", "apple", "melon", "pear"),
value1 <- c(2, 1, 2, 0, 1),
value2 <- c(2, 0, 0, 2, 0),
value3 <- c(0, 2, 2, 1, 1)
)
allwords <- c("apple", "pear", "banana", "ananas", "melon", "cherry")
I want to create a new set of vectors, each one dedicated to one of the words in allwords, reporting the value that each participant assigned to that word (NA if no value assigned). This is the output I am trying to get:
apple pear banana ananas melon cherry
2 1 0 2 1 0
NA 2 0 NA NA NA
2 0 2 NA NA NA
NA 1 2 NA NA NA
NA 1 1 NA NA NA
I wrote this function to achieve this
value.f <- function(y){
values.w[[y]] <- NA
value.var <- values.w[[y]]
value.var[which(data$words1 == y)] <- data$value1
value.var[which(data$words2 == y)] <- data$value2
value.var[which(data$words3 == y)] <- data$value3
}
attach(data)
values.w <- list()
values.w <- lapply(allwords, value.f)
names(values.w) <- c(allwords)
But what I get is, for each word, the content of data$value3.
apple pear banana ananas melon cherry
0 0 0 0 0 0
2 2 2 2 2 2
2 2 2 2 2 2
1 1 1 1 1 1
1 1 1 1 1 1
I do not understand what I am doing wrong, but I have struggled a lot to use character vectors in lapply functions before so I guess that is the issue here.
I tried with eval(parse(text=), I tried with paste0, but I could nor make it to work.