转换列名中所有以“字符串”开头的非NA值到1& NA到0 [英] Convert all Non NA values in column name starting with "string" to 1 & NA to 0
本文介绍了转换列名中所有以“字符串”开头的非NA值到1& NA到0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我将使用虹膜进行再现性
df<-虹膜%&%;%
突变(Species2 = Species) %>%
map_df(。,function(x){x [sample(c(TRUE,NA),prob = c(0.8,0.2),size = length(x),replace = TRUE)]}} )%&%;%
mutate(across(where(starts_with( Species)),as.factor))
我创建了另一列Species2&随机输入的NA,我要做的是将两列(物种和物种2)中的所有非NA值都转换为 1。 NA在这两列中均为0
我想到了在&作为.numeric表示,尽管如此,它仍然不起作用。 ;)),as.numeric))
解决方案
在 dplyr
,您可以执行以下操作:
library(dplyr)
df%> %mutate(across(starts_with( Species),〜as.integer(!is.na(。))))
在基数R中,可以这样操作:
cols<-grep('^ Species',names(df))
df [cols]<-+(!is.na(df [cols]))
I'll use to iris for reproduciblity
df <- iris %>%
mutate(Species2=Species) %>%
map_df(., function(x) {x[sample(c(TRUE, NA), prob = c(0.8, 0.2), size = length(x), replace = TRUE)]}) %>%
mutate(across(where(starts_with("Species")),as.factor))
I have created another column Species2 & randomly entered NA, what I want to do is convert all non NA values in two columns (Species & Species 2) to 1 & NA's in those two columns to 0
I thought of using across & as .numeric for this, somehow it doesn't work though.
df %>% mutate(across(where(starts_with("Species")),as.numeric))
解决方案
In dplyr
, you can do :
library(dplyr)
df %>% mutate(across(starts_with("Species"), ~as.integer(!is.na(.))))
In base R, this can be done as :
cols <- grep('^Species', names(df))
df[cols] <- +(!is.na(df[cols]))
这篇关于转换列名中所有以“字符串”开头的非NA值到1& NA到0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文