在dataframe中的特定位置创建列
我想在特定位置创建一个新变量。我可以使用在dataframe中的特定位置创建列,r,tidyverse,tibble,R,Tidyverse,Tibble,我想在特定位置创建一个新变量。我可以使用mutate创建变量,然后使用select重新排序,但我更喜欢使用tibble:add_column方法 这是iris数据集的一个简单示例: library(tidyverse) ## This works fine iris %>% mutate(With_mutate = ifelse(Sepal.Length > 4 & Sepal.Width > 3 , TRUE, FALSE)) %>% sel
mutate
创建变量,然后使用select
重新排序,但我更喜欢使用tibble:add_column
方法
这是iris数据集的一个简单示例:
library(tidyverse)
## This works fine
iris %>% mutate(With_mutate = ifelse(Sepal.Length > 4 & Sepal.Width > 3 , TRUE, FALSE)) %>%
select(Sepal.Length:Petal.Width, With_mutate, everything()) %>%
head()
## This works also
iris %>% add_column(With_add_column = "Test", .before = "Species") %>%
head()
## This doesn't work
iris %>% add_column(With_add_column = ifelse(Sepal.Length > 4 & Sepal.Width > 3 , TRUE, FALSE), .before = "Species") %>%
head()
Error in ifelse(Sepal.Length > 2 & Sepal.Width > 1, TRUE, FALSE) :
object 'Sepal.Length' not found
如果有人能告诉我为什么我的
ifelse
语句不能与add\u column
一起使用,我将不胜感激。原因是mutate
或summary
等根据指定的符号获取列值,但这里的add\u column
不能。因此,我们可以使用$
iris %>%
add_column(With_add_column = ifelse(.$Sepal.Length > 4 &
.$Sepal.Width > 3 , TRUE, FALSE), .before = "Species") %>%
head()
#Sepal.Length Sepal.Width Petal.Length Petal.Width With_add_column Species
#1 5.1 3.5 1.4 0.2 TRUE setosa
#2 4.9 3.0 1.4 0.2 FALSE setosa
#3 4.7 3.2 1.3 0.2 TRUE setosa
#4 4.6 3.1 1.5 0.2 TRUE setosa
#5 5.0 3.6 1.4 0.2 TRUE setosa
#6 5.4 3.9 1.7 0.4 TRUE setosa
为了使其紧凑,逻辑条件的值是TRUE/FALSE
,因此,我们不需要ifelse
即
add_column(With_add_column = .$Sepal.Length > 4 & .$Sepal.Width > 3, .before = "Species")
可以替换第二步非常感谢@akrun提供了这个超级快速的答案。还有一个很好的建议,就是去掉那些确实无用的
ifelse