首页 > 解决方案 > 如何隐藏列表中数据框的列类型?

问题描述

我在名为 df.list 的列表中有以下两个数据框

df1 <- data.frame(name=c("a","b","c"),total=c("1","2","3"),other=c("100","200","300"))
df2 <- data.frame(name=c("d","e","f"),total=c("4","5","6"),other=c("100","200","300"))



df.list <- list(df1,df2)

[[1]]
  name total other
1    a     1   100
2    b     2   200
3    c     3   300

[[2]]
  name total other
1    d     4   100
2    e     5   200
3    f     6   300

我希望能够遍历列表中的每个数据框并将totalandother列转换为数字,并将其分配回 df.list

我尝试了以下方法,但似乎不起作用

lapply(df.list, function(x) as.numeric(x[2:3]))

标签: r

解决方案


We may use type.convert directly on the list

df.list2 <- type.convert(df.list, as.is = TRUE) 

-checking the structure

 str(df.list2)
List of 2
 $ :'data.frame':   3 obs. of  3 variables:
  ..$ name : chr [1:3] "a" "b" "c"
  ..$ total: int [1:3] 1 2 3
  ..$ other: int [1:3] 100 200 300
 $ :'data.frame':   3 obs. of  3 variables:
  ..$ name : chr [1:3] "d" "e" "f"
  ..$ total: int [1:3] 4 5 6
  ..$ other: int [1:3] 100 200 300

If we want to loop, then as.integer/as.numeric works on vectors. So, we need to loop again

df.list2 <- lapply(df.list, function(x) {
             x[2:3] <- lapply(x[2:3], as.integer)
             x})

推荐阅读