如何将一组列复制到新行?

时间:2018-02-21 14:56:52

标签: r excel vba reshape spss

很抱歉,如果之前已经回答过,我甚至不确定如何搜索它。我对R,VBA或SPSS中的任何自动化解决方案感到满意。

我有一大堆这样的人口统计数据:

ID <- c(1, 2, 3, 4, 5)
State <- c("FL", "FL", "FL", "FL", "FL")
County <- c("Lake", "Lake", "Lake", "Orange", "Orange")
Household <- c (2, 1, 3, 2, 1)
First.Gender <- c("Male", "Female", "Male", "Female", "Male")
Second.Gender <- c("Male", "-", "Female", "Female", "-")
Third.Gender <- c("-", "-", "Male", "-", "-")

Gender_Example <- data.frame(ID, State, County, Household, First.Gender, Second.Gender, Third.Gender)

我想找到一种方法来根据列中的内容创建新行(不创建空行)。看起来像这样:

ID_i <- c(1, 1, 2, 3, 3, 3, 4, 4, 5) # _i designates my ideal set
State_i <- c("FL", "FL", "FL", "FL", "FL", "FL", "FL", "FL", "FL")
County_i <- c("Lake", "Lake", "Lake", "Lake", "Lake", "Lake", "Orange", "Orange", "Orange")
Household_i <- c(2, 2, 1, 3, 3, 3, 2, 2, 1)
Gender_i <- c("Male", "Male", "Female", "Male", "Female", "Male", "Female", "Female", "Male")

Gender_ideal <- data.frame(ID_i, State_i, County_i, Household_i, Gender_i)

如果已经问过这个问题,那么我很高兴只有一个链接。谢谢!

2 个答案:

答案 0 :(得分:3)

- [R

在R中,您最好的选择是来自“data.table”的melt(它允许您使用“模式”来识别您的度量变量。使用它,您可以这样做:

library(data.table)
melt(setDT(Gender_Example), measure.vars = patterns("Gender$"))[value != "-"]

或者,有“tidyverse”方法。

library(tidyverse)
Gender_Example %>%
  gather(variable, value, ends_with("Gender")) %>%
  filter(value != "-")

SPSS

在SPSS中,您需要查看varstocases。有一个非常好的writeup here that should help you get started

的Excel

这可能取决于您使用的Excel版本。如果您使用的是2016,则可以对数据使用数据透视表向导,然后双击总计以访问本来用于创建表的基础“长”表。

该流程概述为at this video

或者,您可以使用Tableau reshaping tool

所述的at this video

答案 1 :(得分:1)

这可能有所帮助

library(reshape2)

Gender_ideal <- melt(Gender_Example, id=c(names(Gender_Example)[1:4]))
rows.to.remove <- which(Gender_ideal$value == "-")
Gender_ideal <- Gender_ideal[-rows.to.remove,]
Gender_ideal
   ID State County Household      variable  value
1   1    FL   Lake         2  First.Gender   Male
2   2    FL   Lake         1  First.Gender Female
3   3    FL   Lake         3  First.Gender   Male
4   4    FL Orange         2  First.Gender Female
5   5    FL Orange         1  First.Gender   Male
6   1    FL   Lake         2 Second.Gender   Male
8   3    FL   Lake         3 Second.Gender Female
9   4    FL Orange         2 Second.Gender Female
13  3    FL   Lake         3  Third.Gender   Male