所以我有一個符號和值的記憶測驗。正確的值以 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
uj5u.com熱心網友回復:
使用可重現的示例總是更容易,但根據您的描述,您的資料保存在資料框中(我們稱之為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"))
uj5u.com熱心網友回復:
下面的函式接受您的輸入 (x) 并將其與正確的向量對應。如果輸入向量中的順序很重要,您可以將引數順序設定為 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/340028.html
標籤:r
上一篇:使用purrr::map*()將嵌套串列元素分配給另一個嵌套串列
下一篇:R中資料幀中NA值的列印行
