【发布时间】:2020-08-28 23:02:44
【问题描述】:
我经常进行这种数据清理,我试图将 Qualtrics 调查中以宽格式收集的数据转换为长格式。我通常有例如我针对每个国家/地区多次提出的两个主要问题、一些协变量和一个 ID 变量。下面的代码以这种格式创建示例数据。我想将数据从下面的宽格式转换为长格式,其中一列是国家,两列是主要问题,一列是协变量,一列是 ID 变量。我一直在这样做,但我绝对确定这是一种糟糕、低效的方式,但我找不到如何更有效地完成这项确切任务的示例。如果有人可以向我展示一种更有效的方法,我将不胜感激,最好使用 base R 或 tidyverse。
require(tidyr)
#make example data
dfLength = 500
wide = data.frame(happy_Belgium = runif(dfLength), happy_US= runif(dfLength), happy_UK= runif(dfLength), angry_Belgium= runif(dfLength), angry_US= runif(dfLength), angry_UK= runif(dfLength), id = 1:dfLength, other_variable = runif(dfLength))
#Make an individual long dataframe for each measure
longHappy = wide %>%
gather(key="country", value="happy", happy_Belgium:happy_UK)
longAngry = wide %>%
gather(key="country", value="angry", angry_Belgium:angry_UK)
#Make a variable for the country based on the format of the question titles
longHappy$country = substring(longHappy$country, 7, nchar(longHappy$country))
longAngry$country = substring(longAngry$country, 7, nchar(longAngry$country))
#Merge the two long variables
long = merge(longHappy, longAngry)
#Get rid of columns I don't need
keeps = c("id", "other_variable", "happy", "angry", "country")
long = long[,names(long) %in% keeps]
【问题讨论】:
标签: r tidyverse data-cleaning