如何计算具有特定值的列

  • 本文关键字:何计算 计算 r
  • 更新时间 :
  • 英文 :


所以我有一个符号和值的记忆测试。正确的值按2、4、6、8、10、12这样的顺序保存。如果都是正确的,我想添加一个值为6的新列。例如,如果2是3,那么新列应该只包含5。我希望你能理解我在努力做什么。正确的顺序是

2 4 6 8 10 12

答案

3 4 6 8 10 12 --> first is false
2 10 6 8 10 12 --> second is false
2 4 6 8 10 12 --> all correct

现在我想添加一个新列,并计算正确的个数。它看起来像这样:

5
5
6

使用可重复的示例总是更容易,但从您的描述中,您的数据保存在数据帧中(让我们称之为df),看起来像这样:

df
#>           first second third fourth fifth sixth
#> Subject 1     3      4     6      8    10    12
#> Subject 2     2     10     6      8    10    12
#> Subject 3     2      4     6      8    10    12

在这种情况下,您可以添加一个列给出总分,如下所示:

df$Score <- apply(df, 1, function(x) sum(x == 2 * 1:6))

现在你的数据帧是这样的:

df
#>           first second third fourth fifth sixth Score
#> Subject 1     3      4     6      8    10    12     5
#> Subject 2     2     10     6      8    10    12     5
#> Subject 3     2      4     6      8    10    12     6

数据使用

df <- structure(list(first = c(3L, 2L, 2L), 
second = c(4L, 10L, 4L), 
third = c(6L, 6L, 6L), 
fourth = c(8L, 8L, 8L), 
fifth = c(10L, 10L, 10L), 
sixth = c(12L, 12L, 12L)), 
class = "data.frame", 
row.names = c("Subject 1", "Subject 2", "Subject 3"))

下面的函数接受输入(x)并将其指向正确的向量。如果输入向量的顺序很重要,可以将参数order设置为TRUE。请看下面的4个例子:

# 4 dummy vectors to test the function
v1 <- c(3, 4, 6, 8, 10, 12)
v2 <- c(2, 5, 6, 8, 10, 12)
v3 <- c(2, 4, 6, 8, 10, 12)
v4 <- c(4, 2, 6, 8, 10, 12)# A 4th example where the order is reversed
# Write a function. You can edit what "correct" looks like.
# x is your object, and order is a logical argument.
# When order = FALSE (default), what counts is that all the values in your vector are in the "correct" vector.
# When order = TRUE, the order must be respected too.
check <- function(x, order = FALSE) {
correct <- seq(2, 12, by = 2)
if(!order) {
return(length((x %in% correct)[(x %in% correct)])) 
} else {
return(length(which(c(order(v4) - order(correct)) == 0)))
}
}
check(v1) # [5]
check(v2) # [5]
check(v3) # [6]
check(v4) # [6]
check(v4, order = TRUE) # [4]

如果你的向量是数据帧的行:

# Your dataframe
df <- data.frame(t(matrix(c(v1, v2, v3, v4), ncol = v4, 
dimnames = list(c("first", "second", "third", "fourth", "fith", "sixth"), c("v1", "v2", "v3", "v4")))))
# Apply the function check() on every rows:
df$score <- apply(df, 1, function(x) check(x))
df$score_order <- apply(df, 1, function(x) check(x, order = TRUE))

依次

df
#    first second third fourth fith sixth score score_order
# v1     2      5     6      8   10    12     5           4
# v2     2      5     6      8   10    12     5           4
# v3     4      2     6      8   10    12     6           4
# v4     4      2     6      8   10    12     6           4

相关内容

  • 没有找到相关文章

最新更新