gpt4 book ai didi

在r中重新格式化数据

转载 作者:行者123 更新时间:2023-12-02 21:15:18 26 4
gpt4 key购买 nike

我有以下类型的数据,尽管在实际数据集中集合和个体的级别相当高:

set <- c(rep(1,6), rep(2,6))
Indvidual <- c(rep (c("IndvA", "IndvA", "IndvB", "IndvB", "IndvC", "IndvC"), 2))
leftposition <- c(10, 10,0 ,0, 0, 0, 40, 40, 30, 30, 20, 20 )
rightposition <- c(20, 20,20,20, 30, 30, 50, 50, 40, 40, 60, 60 )
leftmark <- c( 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21 , 23 )
rightmark <- c( 2, 4, 6, 8, 10, 12,14, 16, 18, 20, 22, 24 )

myd <- data.frame (set, Indvidual,leftposition,rightposition, leftmark, rightmark)
myd

set Indvidual leftposition rightposition leftmark rightmark
1 1 IndvA 10 20 1 2
2 1 IndvA 10 20 3 4
3 1 IndvB 0 20 5 6
4 1 IndvB 0 20 7 8
5 1 IndvC 0 30 9 10
6 1 IndvC 0 30 11 12
7 2 IndvA 40 50 13 14
8 2 IndvA 40 50 15 16
9 2 IndvB 30 40 17 18
10 2 IndvB 30 40 19 20
11 2 IndvC 20 60 21 22
12 2 IndvC 20 60 23 24

在新数据集中,除了第一列为“Individual”之外,其余列都将是唯一的(leftpostion、rightposition)

sort (unique (c(leftposition, rightposition)))
[1] 0 10 20 30 40 50 60

现在,对于 set = 1,我想为个体添加值(请注意,每个个体已重复两次,这是预期的)。每个个体都有两个值 - 一个添加到左侧(左侧位置),另一个添加到右侧(右侧位置)。实际要打印到左边或右边的数据分别在leftmark和rightmark中。因此,对于第一组,组织的数据将如下所示:

enter image description here

然后set2(或n组数据)将被添加到同一个表中。末尾的任何空白都将用 NA 或任何指定的值(例如“-”)填充。

enter image description here

感谢您的帮助:

最佳答案

library(reshape2)
library(plyr)
#Make indviduals unique
myd <- ddply(myd, .(set, Indvidual), transform,
Indvidual = paste(Indvidual, order(Indvidual), sep = "_"))

# bind positions together

myd_molten <- melt(myd, id.vars=c("set", "Indvidual"))
marks <- grep("mark", myd_molten$variable)
levels(myd_molten$variable) <- rep(c("left", "right"), 2)
myd_pos <- myd_molten[-marks,]
names(myd_pos)[4] <- "position"
myd_mark <- myd_molten[marks,]
myd_binded <- cbind(myd_pos, mark = myd_mark$value)

#cast it into the desired form and get the names right
#I could have done the names with gsub but I didn't want to mess with regexpr

ans <- dcast(Indvidual ~ position, value.var = "mark", data = myd_binded)
ans$Indvidual <- do.call(rbind, strsplit(ans$Indvidual, "_"))[,1]
ans

Indvidual 0 10 20 30 40 50 60
1 IndvA NA 1 2 NA 13 14 NA
2 IndvA NA 3 4 NA 15 16 NA
3 IndvB 5 NA 6 17 18 NA NA
4 IndvB 7 NA 8 19 20 NA NA
5 IndvC 9 NA 21 10 NA NA 22
6 IndvC 11 NA 23 12 NA NA 24

关于在r中重新格式化数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11988746/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com