R 转换列名中以“开始”开头的所有非NA值;“字符串”;至1&;NA到0

R 转换列名中以“开始”开头的所有非NA值;“字符串”;至1&;NA到0,r,dplyr,tidyverse,R,Dplyr,Tidyverse,我将使用iris进行复制 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")),

我将使用iris进行复制

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))
  

dplyr
中,您可以执行以下操作:

library(dplyr)
df %>% mutate(across(starts_with("Species"), ~as.integer(!is.na(.))))
在base R中,这可以通过以下方式完成:

cols <- grep('^Species', names(df))
df[cols] <- +(!is.na(df[cols]))
cols使用

df_NA<-which(df==NA)
df_Val<-which(df>=0)
df[df_NA]<-0
df[df_Val]<-1

df_nasu因为它只适用于以“物种”开头的列,所以有更好的方法吗。我已经使用iris进行重现性分析,但是有很多列(从物种开始),您应该删除
中的
位置,因为您是根据名称选择列的。目前,您当前的示例给出了一个错误。感谢Ronak,接下来我将它们相加到一个总计列中,我做了这个df%>%mutate(以(“物种”)开头的跨区,~As.integer(!is.na()))%%>%mutate(total=cross(以(“物种”)开头的跨区,~As.integer(!is.na()),给出了一个错误的输出,不知为什么:
df%>%mutate(以(“物种”)开头的跨区,~As.integer(!is.na)()),sum=rowSums(选择(,以('Species'))开始)
是的,任何关于我的代码在注释中给出错误输出的想法都被认为是按列运行的。你告诉它对两列求和,并将其存储在一列中,这就是它返回错误的原因。
df_NA<-which(df==NA)
df_Val<-which(df>=0)
df[df_NA]<-0
df[df_Val]<-1