R语言 整形函数未正确Map值

omhiaaxx  于 2023-02-06  发布在  其他
关注(0)|答案(2)|浏览(110)

我正在进行一个受试者内设计,研究参与者如何在各种变量(效价、唤醒等)上对20个视频进行评分,并试图将我的宽格式df转换为长格式,所以它看起来像这样......
| 识别号|视频_类型|价|觉醒|
| - ------|- ------|- ------|- ------|
| 一百二十三|喜剧|1个|一百|
| 一百二十三|戏剧|四个|八十二|
当前的宽格式如下所示:
| 识别号|Comedy.valence|Comedy.arousal|Comedy.rating|Drama.valence|Drama.arousal|
| - ------|- ------|- ------|- ------|- ------|- ------|
| 一百一十一|1个|1个|一百|五个|七|
| 九九九|六个|四个|八十二|三个|八个|
当我使用下面的代码时,长数据集的所有列名都是正确的,但是值没有正确Map(例如,valence的值被放在aroirs下,aroirs的值被放在rating下,等等)。

reshape(videoratings, direction = "long", 
        varying=c(1:23), 
        timevar = "video",
        times = c("Comedy", "Drama", "Action"),
        v.names = c("valence", "arousal", "rating"),
        idvar = "ResponseId")

有人知道怎么修吗?

yh2wf1be

yh2wf1be1#

我创建了一个与您的示例类似的示例数据集

df <- data.frame(ID=c(111,999), Comedy.valence=c(1, 6), Comedy.arousal=c(1,4), Comedy.rating=c(100,82), Drama.valence=c(5,3), Drama.arousal=c(7,8), Drama.rating=c(20,80))

然后,我应用如下所示的整形:

df2 <- reshape(df, varying = 2:7, direction = "long", idvar = "ID", timevar = "Video_Type", v.names = c("valence", "arousal", "rating"), times = c("Comedy", "Drama"))

row.names(df2) <- NULL

df2

输出如下所示:

ID Video_Type valence arousal rating
1 111     Comedy       1     100      1
2 999     Comedy       4      82      6
3 111      Drama       7      20      5
4 999      Drama       8      80      3

我对代码做了一些修改:

df2 <- reshape(df, 
        varying = 2:7, 
        direction = "long", 
        idvar = "ID", 
        timevar = "Video_Type", 
        v.names = unlist(unique(lapply(strsplit(names(df), split="\\.")[2:7], '[[', 2))), 
        times = unlist(unique(lapply(strsplit(names(df), split="\\.")[2:7], '[[', 1))))

row.names(df2) <- NULL

df2

我想这取决于您有多少列,您可以修改varyinglapply中的列索引

umuewwlo

umuewwlo2#

只需要切换名称。这不能使用split =参数来反转,因此使用sub函数

reshape(setNames(df, sub("(\\w+).(\\w+)","\\2.\\1", names(df))), -1, dir='long', idv = 'ID')

            ID   time valence arousal rating
111.Comedy 111 Comedy       1       1    100
999.Comedy 999 Comedy       6       4     82
111.Drama  111  Drama       5       7     20
999.Drama  999  Drama       3       8     80

相关问题