r - Use of list in for loop -
i in trouble part of code. i'm beginner , tried make loop list construct different data.frame. let's see
df<-data head(data) col1 col2 col3 1 13 2 34 2 46 b 1 23 d 3 56 b 2 31 df_a<-data[which(data$col1=="a") df_b<-data[which(data$col1=="b") df_c<-data[which(data$col1=="c") df_d<-data[which(data$col1=="d") list<-c("_a","_b","_c","_d") (i in list){ paste0("df",i,"1")<-data(which(paste0("df",i)$col2==1)) paste0("df",i,"2")<-data(which(paste0("df",i)$col2==2)) paste0("df",i,"3")<-data(which(paste0("df",i)$col2==3))
in case aim construct different dataframe original dataframe. in context little tricky i'm not using way if syntax similar.
the problem adjunction of paste name of data frame , "$". r return error message :
error in which(paste0("df", i, "1")$col2 == 1) : erreur d'évaluation de l'argument 'x' lors de la sélection d'une méthode pour la fonction 'which' : error in paste0("df", i, "1")$col2 : $ operator invalid atomic vectors
do have idea resolve problem ?
if i'm interpreting question correctly, in order need exactly, need combination of assign
, eval
, , parse
:
df <- data.frame(col1 = c("a", "a", "a", "b", "d", "b"), col2 = c(1, 2, 2, 1, 3, 2), col3 = c(13 ,34, 46, 23, 56, 31)) df_a<-df[which(df$col1=="a"), ] df_b<-df[which(df$col1=="b"), ] df_c<-df[which(df$col1=="c"), ] df_d<-df[which(df$col1=="d"), ] list <- c("_a","_b","_c","_d") (i in list) { assign(paste0("df", i, "1"), df[eval(parse(text = paste0("which(df", i, "$col2 == 1)"))), ]) assign(paste0("df", i, "2"), df[eval(parse(text = paste0("which(df", i, "$col2 == 2)"))), ]) assign(paste0("df", i, "3"), df[eval(parse(text = paste0("which(df", i, "$col2 == 3)"))), ]) }
if goal perform operations on these different groups of data, may want package dplyr
's group_by()
, provides cleaner way perform grouped operations.
another, cleaner, way using split()
function store each of splits in 1 list:
split_dfs <- split(df, df$col1) split_dfs <- lapply(split_dfs, function(x) split(x, x$col2))
Comments
Post a Comment