【问题标题】:Matching "uniqid" with corresponding sex and age.将“uniqid”与相应的性别和年龄相匹配。
【发布时间】:2016-09-20 19:53:33
【问题描述】:

我有一个数据框 imcds 来自一项调查,该调查向住户询问了家庭中每个人的性别和年龄信息。因此,户主将是第 1 个人,其余的人将是第 2、3、4 个人 .. 等等......因此:

uniqid  Age1  Age2  Age3  Sex1  Sex2  Sex3

1012501  9     7      5     1    2      1
1012502  9     7      5     1    2      1
1012503  9     7      5     1    2      1
1012601  8     5      NA    2    1      NA
1012602  8     5      NA    2    1      NA

uniqid 的前五个数字是家庭 ID,后两个是个人标识符。因此,Person 1012503 的 Age 值为 Age3 (5),Sex 为 Sex3 (1)。我想要做的是将数据框imcds 重塑成这样的:

uniqid  Age  Sex  

1012501  9     1      
1012502  7     2      
1012503  5     1      
1012601  8     2      
1012602  5     1   

每个uniqid 及其对应的SexAge 值。数据框有583 个变量的2095 个obs。我需要一个循环吗?我能做些什么?

【问题讨论】:

    标签: r reshape


    【解决方案1】:

    我们从 'uniqid' 列中提取 6 到 7 个字符的子字符串,用它来创建行/列索引 ('ind'),从 'Age' 列和 'Sex' 列中提取相应的元素,然后 @ 987654321@ 与数据集的第一列。

    ind <- cbind(1:nrow(df1), as.numeric(substr(df1$uniqid, 6,7)))
    Age <- df1[grep("Age", names(df1))][ind]
    Sex <- df1[grep("Sex", names(df1))][ind]
    df2 <- cbind(df1[1], Age, Sex)
    df2
    #   uniqid Age Sex
    #1 1012501   9   1
    #2 1012502   7   2
    #3 1012503   5   1
    #4 1012601   8   2
    #5 1012602   5   1
    

    【讨论】:

    • 谢谢!那效果很好。但是我该如何修改 df 本身呢?将AgeSex 添加为原始imcds data.frame 的新列??然后只需删除Age1Age2、...Age7 并留下一个独特的列,其中包含每个uniqid 的年龄和性别。
    • @GracielaCarrillo 您可以使用df2 &lt;- cbind(df1[1], ... 创建一个新对象(更新帖子
    • @GracielaCarrillo 如果我们需要在原始数据集中创建新列,只需执行df1[c("Age", "Sex")] &lt;- list(Age, Sex)
    猜你喜欢
    • 2018-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-12
    • 1970-01-01
    相关资源
    最近更新 更多