gpt4 book ai didi

R:按分组变量将简单函数应用于特定列

转载 作者:行者123 更新时间:2023-12-04 11:40:07 25 4
gpt4 key购买 nike

我有一个数据集,每个人有 2 个观察值。
数据集中有 100 多个变量。
我想用相同变量的可用数据填写每个人的缺失数据。我可以使用 dplyr mutate 函数手动执行此操作,但是对于需要填充的所有变量执行此操作会很麻烦。

这是我尝试过的,但失败了:

> # Here's data example
> # https://www.dropbox.com/s/a0bc69xgxhaeguc/data_xlsc.xlsx?dl=0
> # I have already attached it to my working space
>
> names(data)
[1] "ID" "Age" "var1" "var2" "var3" "var4" "var5" "var6" "var7" "var8" "var9"
> head(data)
Source: local data frame [6 x 11]

ID Age var1 var2 var3 var4 var5 var6 var7 var8 var9
1 1 50 27.5 1.83 92.0 NA NA NA NA NA 5.1
2 1 NA NA NA NA 3.54 30.2 27.9 64.34 60.8 NA
3 2 51 33.7 1.77 105.6 NA NA NA NA NA 5.2
4 2 NA NA NA NA 4.05 36.4 38.7 67.75 63.7 NA
5 3 43 26.3 1.84 89.1 NA NA NA NA NA 4.8
6 3 NA NA NA NA 3.77 24.4 21.9 67.97 64.2 NA

> # As you can see above, for each person (ID) there are missing values for age and other variables.
> # I'd like to fill in missing data with the available data for each variable, for each ID
>
> #These are the variables that I need to fill in
> desired_variables <- names(data[,2:11])
>
> # this is my attempt that failed
>
> data2 <- data %>% group_by(ID) %>%
+ do(
+ for (i in seq_along(desired_variables)) {
+ i=max(i, na.rm=T)
+ }
+ )
Error: Results are not data frames at positions: 1, 2, 3

第一人称的期望输出:
  ID Age var1 var2  var3 var4 var5 var6  var7 var8 var9

1 1 50 27.5 1.83 92.0 3.54 30.2 27.9 64.34 60.8 5.1

2 1 50 27.5 1.83 92.0 3.54 30.2 27.9 64.34 60.8 5.1

最佳答案

这是一个可能的 data.table解决方案

library(data.table)  
setattr(data, "class", "data.frame") ## If your data is of `tbl_df` class
setDT(data)[, (desired_variables) := lapply(.SD, max, na.rm = TRUE), by = ID] ## you can also use `.SDcols` if you want to specify specific columns
data
# ID Age var1 var2 var3 var4 var5 var6 var7 var8 var9
# 1: 1 50 27.5 1.83 92.0 3.54 30.2 27.9 64.34 60.8 5.1
# 2: 1 50 27.5 1.83 92.0 3.54 30.2 27.9 64.34 60.8 5.1
# 3: 2 51 33.7 1.77 105.6 4.05 36.4 38.7 67.75 63.7 5.2
# 4: 2 51 33.7 1.77 105.6 4.05 36.4 38.7 67.75 63.7 5.2
# 5: 3 43 26.3 1.84 89.1 3.77 24.4 21.9 67.97 64.2 4.8
# 6: 3 43 26.3 1.84 89.1 3.77 24.4 21.9 67.97 64.2 4.8

关于R:按分组变量将简单函数应用于特定列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31365860/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com