在循环r中更改数据帧

时间:2016-06-28 20:38:22

标签: r loops dataframe

我想通过代码运行许多数据帧。有没有办法在循环中更改数据框名称?

df01$x = rnorm(100)
df02$x = rnorm(100)+2
df03$x = rnorm(100)*2

dflist <- c("df01", 
            "df02",
            "df03")
for (i in 1:length(dflist){
  {
    #complete tasks by changing df name in existing code
    ifelse([[i]]$x > 0,1,[[i]]$x)
}
#I want to do this for a  number of different fuctions, so it is best to change the df name before "$"
    df[[i]]$Varible = aggregate(df$Varible, .. ,..)}

1 个答案:

答案 0 :(得分:0)

考虑与列表中的数据框集合进行交互,而不是传递其名称的字符串文字。在lapply()函数中,您可以处理您的操作,然后甚至将每个操作转换回单个数据框对象:

df01 <- data.frame(x=rnorm(100))
df02 <- data.frame(x=rnorm(100)+2)
df03 <- data.frame(x=rnorm(100)*2)

# LIST OF DATAFRAMES (NAMED WITH LITERALS)
dfList <- list(df01=df01, df02=df02, df03=df03)
head(dfList[[1]])
#            x
# 1  1.3440091
# 2  0.5838570
# 3 -0.2377477
# 4 -1.5059733
# 5 -1.0605490
# 6 -0.8122972

# ITERATIVELY RUN COLUMN OPERATION 
dfList <- lapply(dfList, function(df) {
  df$x <- ifelse(df$x > 0, 1, df$x)
  return(df)
})

# CONVERT LIST ITEMS INTO INDIVIDUAL ENVIRON OBJECTS
list2env(dfList, envir=.GlobalEnv)
head(df01)
#            x
# 1  1.0000000
# 2  1.0000000
# 3 -0.2377477
# 4 -1.5059733
# 5 -1.0605490
# 6 -0.8122972