首页 > 解决方案 > 按名称条件删除列

问题描述

我是 R 新手,我需要解决这个问题,我有一个数据框,其列名具有这种模式:

#Example
¦ 1.1 ¦ 1.2 ¦ 1.3 ¦ 2.1 ¦ 2.2 ¦ 2.3 ¦ 3.1 ¦ 3.2 ¦ 3.3 ¦

如何删除名称具有此条件的数据框中的所有列:

#Suppose x.y colname
(x.y) 
if x>y => delete column 

后:

¦ 1.1 ¦ 1.2 ¦ 1.3 ¦ 2.2 ¦ 2.3 ¦ 3.3 ¦

这是 dput(head(x)) 的输出,其中 x 是我的 df: 在此处输入图像描述 “Código UNU”只是一个 ID

我尝试了 grep 但我做不到。所有的帮助都将受到欢迎和感激!

标签: r

解决方案


您可以使用 baseR根据此条件对列进行索引:

names = as.character(c(1.1, 1.2, 1.3, 2.1, 2.2, 2.3, 3.1, 3.2, 3.3))

df = setNames(rnorm(n = length(names)), names)

df
#        1.1        1.2        1.3        2.1        2.2        2.3        3.1        3.2        3.3 
# -0.4685751 -0.1085529 -0.5613519 -1.0906374  1.0530686 -0.8101930 -0.6015732  1.3895373 -0.6977108 

wrangle <- function(x) {
  list <- strsplit(x, split = "\\.")
  left <- list[[1]][1]
  right <- list[[1]][2]
  return(left <= right) #will be TRUE if desired criteria is met
}

df[unlist(lapply(names, wrangle))] #index using the T/F vector
#        1.1        1.2        1.3        2.2        2.3        3.3 
# -0.9873006  0.6089725  0.2823161  0.3397318 -0.3136084  0.2270087

推荐阅读