Dplyr rowwise 不适用于未命名的位置标识符
Dplyr rowwise not working on unnamed position identifiers
我正在尝试获取数据框中每一行的最短时间。我不知道我将选择的列的名称,但我知道它们将是第一到第五列:
data <- structure(list(Sch1 = c(99, 1903, 367),
Sch2 = c(292,248, 446),
Sch3 = c(252, 267, 465),
Sch4 = c(859, 146,360),
Sch5 = c(360, 36, 243),
Student.ID = c("Ben", "Bob", "Ali")),
.Names = c("Sch1", "Sch2", "Sch3", "Sch4", "Sch5", "Student.ID"), row.names = c(NA, 3L), class = "data.frame")
# this gets overall min for ALL rows
data %>% rowwise() %>% mutate(min_time = min(.[[1]], .[[2]], .[[3]], .[[4]], .[[5]]))
# this gets the min for EACH row
data %>% rowwise() %>% mutate(min_time = min(Sch1, Sch2, Sch3, Sch4, Sch5))
在按行模式下,列符号是否应该 .[[1]]
return 所有值?我也试过按 Student.ID 而不是按行分组,但这没有任何区别
即使在分组期间,列符号 .[[1]]
returns 所有值的原因是 .
实际上并未分组。基本上,.
与您开始使用的数据集相同。因此,当您调用 .[[1]]
时,您实际上是在访问第一列中的所有值。
您可能需要改变数据并添加 row_number
列。这允许您在相应的行号处索引要更改的列。应执行以下操作:
data %>%
mutate(rn = row_number()) %>%
rowwise() %>%
mutate(min_time = min(.[[1]][rn], .[[5]][rn])) %>%
select(-rn)
应该产生:
# Sch1 Sch2 Sch3 Sch4 Sch5 Student.ID min_time
# <dbl> <dbl> <dbl> <dbl> <dbl> <chr> <dbl>
# 1 99 292 252 859 360 Ben 99
# 2 1903 248 267 146 36 Bob 36
# 3 367 446 465 360 243 Ali 243
我正在尝试获取数据框中每一行的最短时间。我不知道我将选择的列的名称,但我知道它们将是第一到第五列:
data <- structure(list(Sch1 = c(99, 1903, 367),
Sch2 = c(292,248, 446),
Sch3 = c(252, 267, 465),
Sch4 = c(859, 146,360),
Sch5 = c(360, 36, 243),
Student.ID = c("Ben", "Bob", "Ali")),
.Names = c("Sch1", "Sch2", "Sch3", "Sch4", "Sch5", "Student.ID"), row.names = c(NA, 3L), class = "data.frame")
# this gets overall min for ALL rows
data %>% rowwise() %>% mutate(min_time = min(.[[1]], .[[2]], .[[3]], .[[4]], .[[5]]))
# this gets the min for EACH row
data %>% rowwise() %>% mutate(min_time = min(Sch1, Sch2, Sch3, Sch4, Sch5))
在按行模式下,列符号是否应该 .[[1]]
return 所有值?我也试过按 Student.ID 而不是按行分组,但这没有任何区别
即使在分组期间,列符号 .[[1]]
returns 所有值的原因是 .
实际上并未分组。基本上,.
与您开始使用的数据集相同。因此,当您调用 .[[1]]
时,您实际上是在访问第一列中的所有值。
您可能需要改变数据并添加 row_number
列。这允许您在相应的行号处索引要更改的列。应执行以下操作:
data %>%
mutate(rn = row_number()) %>%
rowwise() %>%
mutate(min_time = min(.[[1]][rn], .[[5]][rn])) %>%
select(-rn)
应该产生:
# Sch1 Sch2 Sch3 Sch4 Sch5 Student.ID min_time
# <dbl> <dbl> <dbl> <dbl> <dbl> <chr> <dbl>
# 1 99 292 252 859 360 Ben 99
# 2 1903 248 267 146 36 Bob 36
# 3 367 446 465 360 243 Ali 243