Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 通过+;数字数据帧中的1_R_Dataframe_Sum_Upgrade - Fatal编程技术网

R 通过+;数字数据帧中的1

R 通过+;数字数据帧中的1,r,dataframe,sum,upgrade,R,Dataframe,Sum,Upgrade,我有一个关于升级数据帧中的值的问题。数据帧如下所示: P1 P2 P3 P4 P5 P6 A 1 0 0 0 0 0 B 0 1 0 0 0 0 C 0 0 1 0 0 1 D 0 0 0 0 1 0 E 1 0 0 0 0 0 F 0 0 0 1 1

我有一个关于升级数据帧中的值的问题。数据帧如下所示:

    P1    P2   P3   P4   P5   P6
A    1    0    0    0    0    0
B    0    1    0    0    0    0
C    0    0    1    0    0    1
D    0    0    0    0    1    0
E    1    0    0    0    0    0
F    0    0    0    1    1    0
我的问题是,我想将一些值升级+1。这意味着,我有一个变量P1_upgrade,它包含需要升级+1的行。有人能帮我解决这个问题吗?最后一列必须与下一列相似:

> P1_upgrade <- "E"
> P3_upgrade <- "C"
> P5_upgrade <- c("D","D","F")


    P1    P2   P3   P4   P5   P6
A    1    0    0    0    0    0
B    0    1    0    0    0    0
C    0    0    2    0    0    1
D    0    0    0    0    3    0
E    2    0    0    0    0    0
F    0    0    0    1    2    0
>P1\u升级P3\u升级P5\u升级
>m df row.names(df)df
V1 V2 V3 V4 V5
0 0 0 0 0
b 0 0 0 0 0
C000
d 0 0 0 0 0
e 0 0 0 0 0 0

>up dump如果更改存储要更新的变量的方式,此问题可以简化很多,例如:

dat <- structure(c(1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 
0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0), .Dim = c(6L, 6L),
.Dimnames = list(c("A", "B", "C", "D", "E", "F"), c("P1","P2", "P3", "P4", "P5", "P6")))
聚合
按行/列索引的升级:

upg <- aggregate( count ~ row + col , data=upg, sum)

#  row col count
#1   E  P1     1
#2   C  P3     1
#3   D  P5     2
#4   F  P5     1

如果数据框中的每一列都是相同的类型(在本例中总是数字),那么最好使用矩阵,正如阿菲尔在他的回答中所演示的那样。注意使用
亲爱的邮件,我想对大型数据集使用这种方法。因此,我需要找到一个函数来创建upg数据帧。你也能帮我吗?@Lisann-你想用什么创建
upg
data.frame?是否只是
P1\u升级
P3\u升级
等向量?如果是这样,请参阅我的编辑以了解如何做到这一点。
upg <- mget(ls(pattern="_upgrade"))
names(upg) <- gsub("_upgrade","",names(upg))
upg <- data.frame(
         row=unlist(upg),
         col=rep(names(upg),sapply(upg,length)),
         count=1,
         stringsAsFactors=FALSE
        )

#    row col count
#P1    E  P1     1
#P3    C  P3     1
#P51   D  P5     1
#P52   D  P5     1
#P53   F  P5     1
upg <- aggregate( count ~ row + col , data=upg, sum)

#  row col count
#1   E  P1     1
#2   C  P3     1
#3   D  P5     2
#4   F  P5     1
dat <- as.matrix(dat)
dat[ as.matrix(upg[1:2]) ] <- (dat[ as.matrix(upg[1:2]) ] + upg$count)

#  P1 P2 P3 P4 P5 P6
#A  1  0  0  0  0  0
#B  0  1  0  0  0  0
#C  0  0  2  0  0  1
#D  0  0  0  0  3  0
#E  2  0  0  0  0  0
#F  0  0  0  1  2  0