簡體   English   中英

For循環消除多個dfs中的列

[英]For loop to eliminate columns in multiple dfs

我有大約10個數據框。 例如,這里有兩個:

name <- c("A", "B", "C")
name.footnote <- c("this", "that", "the other")
class <- c("one", "two", "three")
class.footnote <- c("blank", "blank", "blank")

df1 <- data.frame(name, name.footnote, class, class.footnote)
df2 <- data.frame(name, name.footnote, class, class.footnote)

當我一次從一列中刪除列時,我的代碼可以正常工作。

library(dplyr)
df1 <- select(df1, -ends_with("footnote"))

我想編寫一個循環以更少的代碼處理兩個df,但是無法使我的循環正常工作。 我不斷收到相同的錯誤消息:

 Error in UseMethod("select_") : no applicable method for 'select_' applied to an object of class "character". 

在下面查看我嘗試過的許多循環代碼中的一些。 我想念什么?

listofDfs <- list("df1","df2")

1。

lapply(listofDfs, function(df){
  df <- select(df, -ends_with("footnote"))
  return(df)
  }
)

2。

for (i in listofDfs){
  i <- select(i, -ends_with("footnote"))
}

定義列表listofDfs <- list(df1,df2)時,請嘗試刪除引號。 由於錯誤狀態,當您用引號引起來時,列表中的元素是字符,而不是select()期望的data.frame

library(dplyr)

listofDfs <- list(df1,df2)

#using lapply
list_out1 <- lapply(listofDfs, function(df){
  df <- select(df, -ends_with("footnote"))
  return(df)
})

#using for loop
list_out2 <- vector("list", length(listofDfs))
for (i in seq_along(listofDfs)){
  list_out2[[i]] <- select(listofDfs[[i]], -ends_with("footnote"))
}

跟進每個評論

您可以使用getassign來處理原始字符列表,並在迭代時在全局環境中操作df。

listofDfs <- list('df1','df2')

invisible(lapply(listofDfs, function(i){
  df <- select(get(i, globalenv()), -ends_with("footnote"))
  assign(i, df, envir = globalenv())
}))

for (i in listofDfs){
  df <- select(get(i, globalenv()), -ends_with("footnote"))
  assign(i, df, envir = globalenv())
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM