【发布时间】:2021-01-23 01:55:25
【问题描述】:
我有一个如下所示的数据框(带有可重现的代码):
# create the table
name <- c("Mary", "John", "Peter")
id1 <- c(50, 30, 25)
id2 <- c(8, 12, 90)
id3 <- c(14, 17, 34)
id4 <- c(9, 67, 89)
id5 <- c(20, 21, 22)
beep <- c(15, 20, 23)
# combine the df
df <- data.frame(name, id1, id2, id3, id4, id5, beep)
# show df
df
name id1 id2 id3 id4 id5 beep
1 Mary 50 8 14 9 20 15
2 John 30 12 17 67 21 20
3 Peter 25 90 34 89 22 23
我想用小于“beep”变量的“id#”将每个单元格重新编码为 1,否则为 0。我尝试了以下方法:
apply(df, 2, function(x) {
ifelse(x < df$beep, 1, 0)})
这会产生以下向量:
name id1 id2 id3 id4 id5 beep
[1,] 0 0 1 1 1 0 0
[2,] 0 0 1 1 0 0 0
[3,] 0 0 0 0 0 1 0
上述向量的问题是我不希望“name”或“beep”变量发生变化。有什么建议吗?
【问题讨论】:
-
您可以
apply到数据框的列子集:apply(df[ , 2:6], 2,...)