如何在管道运算符中使用Apply功能 [英] How to use apply function in a pipe operator
问题描述
我有一个数据框,其中有几个字符列,然后是几个数字列.我想使用%>%运算符添加一个新列,这是每行数字列中的最大值.
I have a dataframe which has a few character columns followed by a few numerical columns. I want to add a new column using the %>% operators which is the highest value from the numerical columns per row.
假设数据框如下所示:
字符1,字符2,值1,值2,值3
character1, character2, value1, value2, value3
字符串",字符串",5、7、4
"string", "string", 5, 7, 4
字符串",字符串",3、4、2
"string", "string", 3, 4, 2
字符串",字符串",2、8、6
"string", "string", 2, 8, 6
然后,新列的第一行应为7,第二行应为4,最后一行应为8.我正在尝试在管道运算符中使用apply函数,但无法正常工作.
Then the new column should be 7 for the first row, 4 for second row and 8 for last row. I am trying to use the apply function in the pipe operator but it's not working properly.
new_df <- old_df %>%
mutate(new_column = apply(value1:value3, 1, max))
它返回错误:数值表达式只有首先使用的XXX值.
It returns error: Numerical expression has XXX values only first used.
我也尝试使用max(value1:value3)而不是apply,但这也不起作用.
I also tried using max(value1: value3) instead of apply but that doesn't work either.
推荐答案
您可以使用 dplyr
中的 rowwise
:
library(dplyr)
df %>%
rowwise() %>%
mutate(new_column = max(c_across(value1:value2)))
# A tibble: 3 x 6
# Rowwise:
character1 character2 value1 value2 valu3 new_column
<chr> <chr> <int> <int> <int> <int>
1 string string 5 7 4 7
2 string string 3 4 2 4
3 string string 2 8 6 8
数据
library(tidyverse)
df <- tibble::tribble(
~character1, ~character2, ~value1, ~value2, ~valu3,
"string", "string", 5L, 7L, 4L,
"string", "string", 3L, 4L, 2L,
"string", "string", 2L, 8L, 6L
)
这篇关于如何在管道运算符中使用Apply功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!