Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/83.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
dplyr中单行上的操作_R_Dplyr - Fatal编程技术网

dplyr中单行上的操作

dplyr中单行上的操作,r,dplyr,R,Dplyr,是否可以对数据帧的单行使用管道执行dplyr操作?例如,假设我有一个数据帧(称为df),并希望对该数据帧的列进行一些操作: df <- df %>% mutate(col1 = col1 + col2) df = data.frame(a = rep(1, 100), b = rep(1,100)) 我展示的第一个例子是: df <- df %>% mutate(a = a + b) df% 变异(a=a+b) 将导致列a_xPlacexHolderxColumn

是否可以对数据帧的单行使用管道执行dplyr操作?例如,假设我有一个数据帧(称为df),并希望对该数据帧的列进行一些操作:

df <- df %>%
mutate(col1 = col1 + col2)
df = data.frame(a = rep(1, 100), b = rep(1,100))
我展示的第一个例子是:

df <- df %>%
mutate(a = a + b)
df%
变异(a=a+b)
将导致列a_xPlacexHolderxColumnaPlacexHolderx对于所有行为2

第二个示例只会导致列a的第一行为2。

mutate()
用于创建列

您可以执行类似于
df[1,1]的操作,您可以
mutate()
case\u when()
进行条件操作

df %>%
    mutate(a = case_when(row_number(a) == 1 ~ a + b,
                         TRUE ~ a))
导致

# A tibble: 100 x 2
       a     b
   <dbl> <dbl>
 1     2     1
 2     1     1
 3     1     1
 4     1     1
 5     1     1
 6     1     1
 7     1     1
 8     1     1
 9     1     1
10     1     1
# … with 90 more rows
#一个tible:100x2
a b
1     2     1
2     1     1
3     1     1
4     1     1
5     1     1
6     1     1
7     1     1
8     1     1
9     1     1
10     1     1
#…还有90行
资料
库(tidyverse)

df Gotcha,dplyr操作只适用于整列而不是单个元素?是的,mutate用于通过使用类似代码的函数(在大括号内)添加新列。我们可以使用类似矩阵的模型编辑FWIW,
数据的单行和列副本。table
很好地做到了这一点:
setDT(df)
df
转换为数据。table,然后
df[1,a:=a+b]
a
更新为
a+b
,仅在第一行。
# A tibble: 100 x 2
       a     b
   <dbl> <dbl>
 1     2     1
 2     1     1
 3     1     1
 4     1     1
 5     1     1
 6     1     1
 7     1     1
 8     1     1
 9     1     1
10     1     1
# … with 90 more rows
library(tidyverse)
df <- tibble(a = rep(1, 100), b = rep(1,100))