【问题标题】:Transform a data frame with the total count of observations (people) into one with rows for each observation (person)将具有观察总数(人)的数据框转换为一个包含每个观察(人)行的数据框
【发布时间】:2017-03-24 19:04:07
【问题描述】:

我有一个这样的数据集:

    > df<-data.frame(gender=c(rep("male",3),rep("female",3)),
    Age=c(rep("old",3),rep("young",3)),VAR=c(rep(1:3),rep(1:3)),
    FEN1=c(21,26,29,30,6,11),FEN2=c(14,55,12,33,9,21),
    FEN3=c(88,23,55,23,14,66))

其中 FEN1、FEN2 和 FEN3 包含属于该组且具有 VAR、Gender、Age、FEN 列的特征的个体总数。

我需要将其更改为一个数据框,其中每一行属于一个人(总共 536 行),具有 VAR、Gender、Age 列的特征。

预期的输出将包含:

  • 21行有信息:男、老、1、FEN1
  • 14行有信息:男、老、1、FEN2
  • 88行有信息:男、老、1、FEN3
  • 26行有信息:男、老、2、FEN1
  • 55行有信息:男、老、2、FEN2
  • 23行有信息:男、老、2、FEN3
  • 等等……

我试图用如下代码手动完成:

    > df2<-as.data.frame(1:536)
    > FEN <- c(rep("FEN1",123), rep("FEN2",144), rep("FEN3",269))
    > df2$FEN<-FEN
    > Gender<-c(rep("male",...)...

但显然它根本没有效率。

【问题讨论】:

  • 最终你可以从宽到长重塑stackoverflow.com/questions/2185252/…,然后使用数字来复制行。或者对于每一行,您从 FEN1、FEN2、FEN3 中获取数字并为以后的 rbind() 构建新的数据帧。

标签: r dataframe data-conversion


【解决方案1】:

这是一种使用基本 R 方法的方法。

# get the vector names that are used to repeat
fenCats <- tail(names(df), 3)
# construct a list of data.frames where the rows have been repeated
# one data.frame for each of the FEN variables
temp <- Map(function(x) df[rep(seq_len(nrow(df)), x), 1:3], df[fenCats])
# combine list of data.frames and add column with FEN categories
dfNew <- cbind(do.call(rbind, temp),
               "fenCats"=rep(fenCats, colSums(df[fenCats])))

我们可以验证行数是否正确

nrow(dfNew) == sum(colSums(df[fenCats])) &
nrow(dfNew) == sum(rowSums(df[fenCats]))
[1] TRUE

作为附加验证,我们还可以通过使用子集和cumsum拉取每个组的第一行来进行快速验证:

dfNew[cumsum(unlist(df[,fenCats])),]
          gender   Age VAR fenCats
FEN1.1.20   male   old   1    FEN1
FEN1.2.25   male   old   2    FEN1
FEN1.3.28   male   old   3    FEN1
FEN1.4.29 female young   1    FEN1
FEN1.5.5  female young   2    FEN1
FEN1.6.10 female young   3    FEN1
FEN2.1.13   male   old   1    FEN2
FEN2.2.54   male   old   2    FEN2
FEN2.3.11   male   old   3    FEN2
FEN2.4.32 female young   1    FEN2
FEN2.5.8  female young   2    FEN2
FEN2.6.20 female young   3    FEN2
FEN3.1.87   male   old   1    FEN3
FEN3.2.22   male   old   2    FEN3
FEN3.3.54   male   old   3    FEN3
FEN3.4.22 female young   1    FEN3
FEN3.5.13 female young   2    FEN3
FEN3.6.65 female young   3    FEN3

【讨论】:

    猜你喜欢
    • 2017-06-14
    • 1970-01-01
    • 2022-11-11
    • 2019-06-04
    • 2023-02-20
    • 1970-01-01
    • 2019-05-02
    • 2021-02-25
    • 2016-09-09
    相关资源
    最近更新 更多