问题
I am trying to run a "for" loop in R to analyze multiple variables. I have a data set ("DataSet") with column names ("AppleTag1", "AppleTag2", "CherryTag1", "CherryTag2"....). The loop is to compare "Tag1" with "Tag2" columns for each unique column name listed in "ColumnName" and obtain a vector with unique values from both columns. My question is how do I refer to the result of a paste function as a variable. I know the first past function used to collect the unique results can be fixed with "align()". However, what about the other two? How can I make sure R analyzes the paste() result "DataSet$AppleTag1" as a variable and not as a "string". Right now, I get a list of "CombineResult_XXX" with "DataSet$AppleTag1, DataSet$AppleTag2," yet I want is for it to test what is inside these two columns and get something like "123, 213, 141, 232". Thank you for your help.
ColumnName <- c("Apple","Cherry","Bubble","Killer","Fat","Glass","Comp","Key")
NameTag <- c(A,B,C,D,E,F,G,H,I,J)
for (i in 1:10) {
paste("CombineResult_",NameTag[i],sep="") <- unique(c(
as.vector(paste("DataSet$",ColumnName[i],"Tag1", sep="")),
as.vector(paste("DataSet$",ColumnName[i],"Tag2", sep=""))))
}
回答1:
You can't use $
with strings for column names. If you want to subset with strings, use the [[
notation. Maybe something like this would be better.
ColumnName <- c("Apple", "Cherry", "Bubble", "Killer", "Fat", "Glass", "Comp", "Key")
NameTag <- c("A","B","C","D","E","F","G","H","I","J")
CombineResult <- lapply(ColumnNames, function(x) {
unique(c(
DataSet[[paste0(x,"Tag1")]],
DataSet[[paste0(x,"Tag2")]]
))
})
names(CombineResult) <- NameTag(seq_along(CombineResult))
Here the results are stored in a named list. You can get them out with CombineResult$A
or CombineResult[["A"]]
来源:https://stackoverflow.com/questions/33614152/using-a-variable-to-refer-to-another-variable-in-r