R ';mydata$列<;-空';功能不正常
这就是功能:R ';mydata$列<;-空';功能不正常,r,R,这就是功能: remove_column <- function(column_vector) { for (column in column_vector) { if (grepl('.y$', column)) { mydata$column <- NULL } } } 这是列向量的样子: c('v1.x', 'v2.y') 当我打印函数时,它返回以下内容: [1] "v1.x" "v2.y" 根据用户的请求,dput(液滴液位(hor
remove_column <- function(column_vector) {
for (column in column_vector) {
if (grepl('.y$', column)) {
mydata$column <- NULL
}
}
}
这是列向量的样子:
c('v1.x', 'v2.y')
当我打印函数时,它返回以下内容:
[1] "v1.x" "v2.y"
根据用户的请求,dput(液滴液位(horsedata[1:5,1:5])(我为此使用的数据):
我们不需要循环来子集列
mydata[!grepl('\\.y$', column_list)]
如果列列表中没有其他列,并且我们希望保留它们(假设“列列表”已排序)
我们可以通过以下方式修改您的函数:
将.y$
更改为\\.y$
作为
表示任何字符,而不仅仅是点
我们使用[
子集数据集,而不是$
在赋值后返回数据集
remove_column@jgozal您可以将其转换为函数(刚刚更新了帖子).这对我不起作用
虽然没有提供太多信息。我希望能给你更多信息,但我没有收到任何控制台错误。我想我刚刚发现了问题的根源。我在第一个函数中传递的列表不是列表,它的类型是字符。我将尝试修复它first@jgozal不重新检查就不清楚了可生成的示例。例如,正如我展示的那样,您可以使用?dput
即dput(droplevels(head(yourdata)),用一个小示例更新您的帖子
@jgozal数据集中是否有其他列不在列列表中?是的,我有其他列。我很抱歉-我将用一个可复制的示例更新帖子,并添加返回我正在处理的列名列表的函数。实际上,它应该是dup\u name只需在中添加perl=TRUE
de>grepl
。它现在对我有效。更新了remove\u column函数。此外,您可以使用向量化函数,而不是循环duplicate\u names
函数。我猜您没有将结果分配给新对象,即merged\u data1。您可以将nm1
更改为小写或大写,然后执行duplicated
i、 e.nm2啊!很好的解决方法
[1] "v1.x" "v2.y"
dput(droplevels(horsedata[1:5, 1:5]))
structure(list(ÿþhorse_name = structure(c(3L, 1L, 2L, 4L, 5L), .Label = c("IM PRETTY FAMES",
"JESS ROYAL BUCKS", "KISS ME IM SUGAR", "LOLAMO", "RUN MADISON RUN"
), class = "factor"), owner_name = structure(c(3L, 2L, 1L, 5L,
4L), .Label = c("Christine Tavares", "Heste Sport, Inc.", "Picov Cattle Co.",
"Procter, Wayne and Carol", "Ruth F. Barbour"), class = "factor"),
program = structure(1:5, .Label = c("1", "2", "3", "4", "5"
), class = "factor"), pp = 1:5, todays_cls = c(61L, 61L,
61L, 61L, 61L)), .Names = c("ÿþhorse_name", "owner_name",
"program", "pp", "todays_cls"), row.names = c(NA, 5L), class = "data.frame")
mydata[!grepl('\\.y$', column_list)]
mydata[setdiff(1:ncol(mydata), grep('\\.y$', column_list))]
remove_column <- function(dat, column_vec) {
for (column in column_vec) {
if (grepl('\\.y$', column, perl=TRUE)) {
dat[column] <- NULL
}
}
dat
}
remove_column(mydata, column_list)
# v1.x v2.x v3
#1 6 1 9
#2 4 11 7
#3 14 15 5
#4 10 2 4
#5 13 4 0
#6 19 14 1
#7 5 1 8
#8 16 12 7
#9 16 13 5
#10 5 0 7
mydata <- structure(list(v1.x = c(6L, 4L, 14L, 10L, 13L, 19L, 5L, 16L,
16L, 5L), v1.y = c(12L, 7L, 14L, 14L, 6L, 18L, 4L, 0L, 10L, 2L
), v2.x = c(1L, 11L, 15L, 2L, 4L, 14L, 1L, 12L, 13L, 0L), v2.y = c(6L,
5L, 7L, 3L, 19L, 4L, 15L, 13L, 14L, 20L), v3 = c(9L, 7L, 5L,
4L, 0L, 1L, 8L, 7L, 5L, 7L)), .Names = c("v1.x", "v1.y", "v2.x",
"v2.y", "v3"), row.names = c(NA, -10L), class = "data.frame")
column_list <- c('v1.x', 'v1.y', 'v2.x', 'v2.y')