R:类似应用的函数返回一个数据帧? [英] R: apply-like function that returns a data frame?
问题描述
我想将一个函数应用于数据帧的每一行。使用apply,结果本身不再是数据帧,更像是列表或矩阵? (我不知道足够多的R可以从我得到的输出中分辨出来,只是它不是一个数据帧)
I want to apply a function to every row of a data frame. Using apply, the result is not itself a data frame again, it looks more like a list or matrix? (I don't know enough R to be able to tell from the output i get, just that it isn't a data frame)
哪个是正确的函数
我想应用到每一行的函数:
The function i want to apply to each row:
map_uri <- function(request){
ret <- request
uri_stem <- uri_map[uri_map[,1] == request["cs-uri-query"],2]
if(length(uri_stem) > 0){
ret <- request
ret["cs-uri-stem"] <- uri_stem
ret["cs-uri-query"] <- "-"
}
if(request["cs-uri-stem"] == "/index.html"){
ret["cs-uri-stem"] = "/"
}
return(ret)
}
我正在尝试什么:
cleansed <- apply(requests, 1, map_uri)
cleansed[,c("cs-uri-query", "cs-uri-stem")]
这给了我错误
Fehler in cleansed [,c( cs-uri-stem, cs-uri-query)]:Indizierung
außerhalbder Grenzen
Fehler in cleansed[, c("cs-uri-stem", "cs-uri-query")] : Indizierung außerhalb der Grenzen
(索引超出范围)
由于某种原因,结构在
[edit]
数据使之可行:
uri_map.tsv http://pastebin.com/XhUuTMqA
uri_map.tsv http://pastebin.com/XhUuTMqA
uri_map <- read.table("http://pastebin.com/raw/XhUuTMqA", sep="\t", header=FALSE)
并为转换函数输入数据:
And input data for the transformation function:
请求<-read.table( http://pastebin.com/ raw / b7ja4rKn ,sep =,header = TRUE)
requests <- read.table("http://pastebin.com/raw/b7ja4rKn", sep=" ", header=TRUE)
推荐答案
您可以使用,但是,对了,结果是矩阵
或列表
。返回到 data.frame
没什么大不了。
You can use the apply family but, you're right, the result is either a matrix
or a list
. Not a big deal though to get back to a data.frame
.
您的函数需要在各列之间返回一致的值(原始 iris
而不是 iris [,1:4]
在下面不起作用,因为 iris $物种
是具有三个级别的因子,其中摘要
从数字列返回6个数字),而这就是可复制会有所帮助。在下面,我使用了 iris
和 summary
:
Your function needs to return something consistent across columns (raw iris
instead of iris[, 1:4]
would not work below, because of iris$Species
which is a factor with 3 levels where summary
returns 6 numeric from a numeric column) and that's where a reproducible would help. Below, I used iris
and summary
:
- 应用:
as.data.frame(apply(iris [,1:4],2,摘要))
- 应用:
as.data.frame(sapply(iris [,1:4],摘要))
- 应用:
do.call(cbind,lapply(iris [,1:4],摘要))
- apply:
as.data.frame(apply(iris[, 1:4], 2, summary))
- sapply:
as.data.frame(sapply(iris[, 1:4], summary))
- lapply:
do.call(cbind, lapply(iris[, 1:4], summary))
这篇关于R:类似应用的函数返回一个数据帧?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!