我对数据框中的升级值有疑问。数据框如下所示:
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
答案 0 :(得分: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
答案 1 :(得分: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
中记录您的升级。将相关项目存储在单个对象(如list
或data.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