R错误:参数意味着行数不同

时间:2016-03-05 12:31:34

标签: r

所以我试图使用for循环在数据帧的几列上运行一个函数。

z <- function(x) gsub("[^\\.\\d]", "", x, perl = TRUE)
data <- cbind(data[1:2], for(i in seq(3, 9)) {y(data[[i]])})

我一直遇到主题

中提到的错误
arguments imply differing number of rows

我所有列中的行数都相同。

我尝试使用lapply,但是虽然它有效,但它会将我应用该函数的列类型转换为factor。列是数值,但最初是从文件中读取的字符(它们存储在文件中)。因此,当我尝试使用lapply后转换为数字时,我得到了数量级别作为输出(如1,​​2,3 ......)

欢迎使用for循环或lapply的任何建议。提前谢谢。

> dput(head(data,3))
structure(list(MCF.Channel.Grouping = structure(c(6L, 6L, 6L), .Label = c("(Other)", 
"Direct", "Display", "Email", "Organic Search", "Paid Search", 
"Referral", "Social Network"), class = "factor"), Device.Category = structure(c(2L, 
1L, 3L), .Label = c("desktop", "mobile", "tablet"), class = "factor"), 
Spend = c("A$503,172.17", "A$375,940.43", "A$92,560.94"), 
Clicks = c("1,545,416", "1,037,740", "291,314"), Impressions = c("7,328,657", 
"3,787,612", "1,178,508"), Data.Driven.Conversions = c("1,697,814.32", 
"1,540,810.43", "430,738.63"), Data.Driven.CPA = c("A$0.30", 
"A$0.24", "A$0.21"), Data.Driven.Conversion.Value = c("A$12,815,842.66", 
"A$13,883,073.58", "A$3,804,800.15"), Data.Driven.ROAS = c("2547.01%", 
"3692.89%", "4110.59%")), .Names = c("MCF.Channel.Grouping", 
"Device.Category", "Spend", "Clicks", "Impressions", "Data.Driven.Conversions", 
"Data.Driven.CPA", "Data.Driven.Conversion.Value", "Data.Driven.ROAS"
), row.names = c(NA, 3L), class = "data.frame")

1 个答案:

答案 0 :(得分:0)

我们可以使用

data[-(1:2)] <- lapply(data[-(1:2)], z)

该函数在不是第一个或第二个的列上运行。输出分配给数据中的相同子集。

原始方法不起作用,因为for循环不会导致保存的输出。通过尝试将其保存为变量来检查:

x <- for(i in seq(3, 9)) {z(data[[i]])}
x
NULL

即使我们保存了循环的内容,也没有捕获任何内容。然后循环运行转储结果。要了解循环如何工作,我们可以在:

中分配值
for ( i in 3:9) data[,i] <- z(data[,i])