如何使用R中的循环从多个数据帧中删除列(数目可以变化)

时间:2018-07-21 06:40:55

标签: r

假设有多个data.frameSales_1Sales_2,...,Sales_max,其中_max是动态的...

所有这些数据集都有一些常见的列,例如"ID",我需要删除它们!

可以在R中使用for循环吗?

也许是这样

for(i in 1:max){
Sales_**i**$ID=NULL #basically I am looking to resolve the variable as data frame name while using the loop
}

3 个答案:

答案 0 :(得分:2)

如果data.frames中有所有list。然后,您可以使用lapply,而不必考虑数据帧名称:

myNames <- c("john", "fred", "steph","joe", "val")
sales   <- c(1000, 2000, 3000, 4000, 2000)

# Start with some example data:
mynrow <- 6
Sales_1 <- data.frame(ID=1:mynrow, seller=sample(myNames, mynrow, TRUE), amount = sample(sales, mynrow, TRUE))
Sales_2 <- data.frame(ID=1:mynrow, seller=sample(myNames, mynrow, TRUE), amount = sample(sales, mynrow, TRUE))
Sales_3 <- data.frame(ID=1:mynrow, seller=sample(myNames, mynrow, TRUE), amount = sample(sales, mynrow, TRUE))

Sales <- list(Sales_1, Sales_2, Sales_3)

lapply(Sales, function(x) x[-1])

答案 1 :(得分:0)

这可以做到:

# Start with some example data:
Sales_1 <- data.frame(id=c(1,2,3), name=c("john", "fred", "steph"))
Sales_2 <- data.frame(id=c(4,2,1), name=c("joe", "val", "kerry"))
Sales_3 <- data.frame(id=c(1,2,3), name=c("jane", "aaron", "don"))


numberOfSalesDataframes <- 3 # Set this to the number of Sales dataframes you have


for (i in 1:numberOfSalesDataframes) {

  # These two lines of code will remove column "id"
  command <- paste0("Sales_", i, "$id", "  <- NULL")
  eval(parse(text=command))

  # Copy the two lines of code from above to remove another column, and so on..
  # command <- paste0("Sales_", i, "$another_column_you_want_to_remove", "  <- NULL")
  # eval(parse(text=command))

}


Sales_1
Sales_2
Sales_3

答案 2 :(得分:-1)

您可以按以下方式使用evalsubstitute

Sales_1 <- data.frame(id = 1:3, other_stuff = letters[1:3])
Sales_2 <- data.frame(id = 4:6, other_stuff = letters[4:6])
Sales_3 <- data.frame(id=  7:9, other_stuff = letters[7:9])

dfs <- sapply(ls()[grepl("^Sales\\_\\d+$", ls())], as.symbol)
for(sym in dfs)
  eval(substitute(x$id <- NULL, list(x = sym)))

Sales_1
#R   other_stuff
#R 1           a
#R 2           b
#R 3           c
Sales_2
#R   other_stuff
#R 1           d
#R 2           e
#R 3           f
Sales_3
#R   other_stuff
#R 1           g
#R 2           h
#R 3           i