r-在数字数据帧中按+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

如果您改变存储要更新的变量的方式,这个问题可以简化很多,例如:

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")))

data.frame中记录您的升级。将相关项存储在单个对象(如listdata.frame)中有几个优点,最显著的是,如果您发现需要对所有项应用通用更改,则可以避免对多个项进行复杂循环。

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

aggregate按行/列索引升级:

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更改为matrix才能工作):

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
> m <- matrix(rep(0,25),ncol=5)
> df <- as.data.frame(m)
> row.names(df) <- c("a","b","c","d","e")
> df
  V1 V2 V3 V4 V5
a  0  0  0  0  0
b  0  0  0  0  0
c  0  0  0  0  0
d  0  0  0  0  0
e  0  0  0  0  0
> up <- c("b","b","c")
# return value to dump b/c we're not interested in it and don't
# want have it clutter the terminal
> dump <- sapply(up, function(r) df[r,] <<- df[r,] + 1)
> df
  V1 V2 V3 V4 V5
a  0  0  0  0  0
b  2  2  2  2  2
c  1  1  1  1  1
d  0  0  0  0  0
e  0  0  0  0  0

最新更新