如何在R中动态更改数据框中的列

问题描述

我想更改定义为变量(dataframe)的tibble / col_name列的值。我尝试了!!col_name,但没有成功。

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter,lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect,setdiff,setequal,union
col_name <- "b" # the column to select

df <- tibble(a = c(1,2,3),b = c(2,4,6))

df %>%
  mutate(b = if_else((b == 6 & a == 3),8,b))  # this works 
#> # A tibble: 3 x 2
#>       a     b
#>   <dbl> <dbl>
#> 1     1     2
#> 2     2     4
#> 3     3     8

# but this doesn't
df %>%
  mutate(!!col_name := if_else((!!col_name == 6 & a == 3),!!col_name))
#> Error: Problem with `mutate()` input `b`.
#> x `false` must be a double vector,not a character vector.
#> i Input `b` is `if_else(("b" == 6 & a == 3),"b")`.
Created on 2020-10-13 by the reprex package (v0.3.0)

解决方法

使用 base

df[ df[,col_name ] == 6 & df$a == 3,col_name ] <- 8

df
#   a b
# 1 1 2
# 2 2 4
# 3 3 8

注意:是的,我知道这个问题是关于“整洁” 的,这只是为了说明为什么对于一些简单的任务,基本解决方案还是一样好/更好。

,

要在RHS上使用#include<iostream> #include<string> using namespace std; int main() { //2 rows int* jagged[2]; //Allocate memeory for the elements in the row 0 jagged[0] = new int[1]; //Allocate memory for the elements in row 1 jagged[1] = new int[5]; //Array to hold the size of each row int Size[2] = { 1,5 },k = 0,number = 100; //User enters the numbers for (int i = 0; i < 2; i++) { int* p = jagged[i]; for (int j = 0; j < Size[k]; j++) { *p = number++; //move the pointer p++; } k++; } k = 0; //Display elements in Jagged array for (int i = 0; i < 2; i++) { int* q = jagged[i]; for (int j = 0; j < Size[k]; j++) { cout << *q << ""; //move the pointer to the next element q++; } cout << endl; k++; //move the pointer to the next row jagged[i]++; } delete[] jagged; return 0; } ,您需要先将!!转换为符号。

col_name

其他替代方法包括使用library(dplyr) df %>% mutate(!!col_name := if_else(!!sym(col_name) == 6 & a == 3,8,!!sym(col_name)))

get

或者没有任何NSE使用df %>% mutate(!!col_name := if_else(get(col_name) == 6 & a == 3,get(col_name)))

.data

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...