Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 如何创建函数并将结果添加为列?_R_Function_Dataframe - Fatal编程技术网

R 如何创建函数并将结果添加为列?

R 如何创建函数并将结果添加为列?,r,function,dataframe,R,Function,Dataframe,如果我有一个数据帧: A B C 1 2 3 4 5 6 7 8 9 我想添加一个D列,它是a、B、C列的总和。我如何编写一个函数来实现这一点,并将结果作为D列添加到数据帧中?一种方法是使用行和: df <- data.frame(a = 1:3, b = 2:4, c = 3:5) df$d <- rowSums(df) df一种方法是使用rowSums: df <- data.frame(a = 1:3, b = 2:4, c = 3:5) df$d <- row

如果我有一个数据帧:

A B C
1 2 3
4 5 6
7 8 9

我想添加一个D列,它是a、B、C列的总和。我如何编写一个函数来实现这一点,并将结果作为D列添加到数据帧中?

一种方法是使用
行和

df <- data.frame(a = 1:3, b = 2:4, c = 3:5)
df$d <- rowSums(df)

df一种方法是使用
rowSums

df <- data.frame(a = 1:3, b = 2:4, c = 3:5)
df$d <- rowSums(df)

df一种方法是使用库dplyr中的mutate:

library(dplyr)
df <- data.frame(a = 1:3, b = 2:4, c = 3:5)

df = df %>%
       mutate(d = a + b + c)
库(dplyr)
df%
变异(d=a+b+c)

一种方法是使用库dplyr中的mutate:

library(dplyr)
df <- data.frame(a = 1:3, b = 2:4, c = 3:5)

df = df %>%
       mutate(d = a + b + c)
库(dplyr)
df%
变异(d=a+b+c)

这是否回答了您的问题?这回答了你的问题吗?非常感谢。我想变异函数就是我需要的。谢谢!我想我需要的是变异函数。