计算因子级别

时间:2018-02-05 20:32:05

标签: r split lapply

我试图在每一行(V1,V2,V3,V4)中找到每个级别(Level_1和Level_2)的列百分比。

这是我的数据:

DF <- read.table(text=
"F1     V1  V2  V3 V4

Level_1 2   10  9   9   
Level_1 7   3   6   7   
Level_1 10  7   7   3   
Level_2 5   6   2   3   
Level_2 4   6   1   6   
Level_2 1   10  3   4"  , header=T)

我希望输出看起来像这样:

F1      V1  V2  V3  V4

Level_1 11% 50% 41% 47%

Level_1 37% 15% 27% 37%

Level_1 53% 35% 32% 16%

Level_2 50% 27% 33% 23%

Level_2 40% 27% 17% 46%

Level_2 10% 45% 50% 31%

到目前为止,这是我的代码:

col_percent <- unsplit(lapply(split(DF, DF$F1), function(x) prop.table(as.table(as.matrix(x[ , 2:ncol(x)])), 2)), DF$F1)

当我运行它时,我收到这些警告:

Warning messages:
1: In x[i] <- value[[j]] :
  number of items to replace is not a multiple of replacement length
2: In x[i] <- value[[j]] :
  number of items to replace is not a multiple of replacement length

代码确实为我提供了我想要的列百分比,但它将它们输出为一个数字向量。谁能帮我弄清楚这里发生了什么?

3 个答案:

答案 0 :(得分:0)

我们可以拆分数据帧,使用lapply执行操作,并将数据帧合并到最终输出。

DF_list <- split(DF, f = DF$F1)

DF_list2 <- lapply(DF_list, function(x){
  x[, -1] <- lapply(x[, -1], function(y) paste0(round(y/sum(y) * 100), "%"))
  return(x)
})

DF2 <- do.call(rbind, DF_list2)
rownames(DF2) <- 1:nrow(DF2)
DF2
#        F1  V1  V2  V3  V4
# 1 Level_1 11% 50% 41% 47%
# 2 Level_1 37% 15% 27% 37%
# 3 Level_1 53% 35% 32% 16%
# 4 Level_2 50% 27% 33% 23%
# 5 Level_2 40% 27% 17% 46%
# 6 Level_2 10% 45% 50% 31%

答案 1 :(得分:0)

您也可以使用:

terraform get

答案 2 :(得分:0)

您可以使用group_by中的dplyr来执行此操作:

df >%>
  group_by(F1)>%>
  mutate(V1_pct = V1/sum(V1),
         V2_pct = V2/sum(V2),
         V3_pct = V3/sum(V3),
         V4_pct = V4/sum(V4)
  ) >%>
  ungroup()