sapply 的 Dataframe 输出不是 DataFrame
我的 sapply 函数的返回值(在一个输入项上)是一个列表而不是数据框。我不明白为什么。我知道 sapply 通常会生成所有返回值的列表;我很困惑为什么单个输入的返回值是一个列表。
这个例子虽然有点傻,但是很能说明问题。
> alphabet <- data.frame(letters = letters, numbers = 1:26)
> word <- c("w", "o", "r", "d")
> w <-sapply(word[1], function(x) {
n <- alphabet[alphabet$letters == x,"numbers"]
df <- data.frame(letter = x, number = n)
return(df)
}, USE.NAMES = F)
# [,1]
# letter "w"
# number 23
输出是一个长度为 2 的列表,尽管 df 应该是一个数据帧。
我希望输出与在匿名函数之外调用 data.frame()
相同:
> data.frame(letter = "w", number = 23)
# letter number
# 1 w 23
为什么我的 sapply 输出与我调用 data.frame 时的形式不同()
在 sapply()
之外?
The return value of my sapply function, on one input item, is a list rather than a data frame. I don't understand why. I know that sapply generally yields a list of all the return values; I'm confused why the return value of a single input is a list.
The example is a bit silly, but it makes the point.
> alphabet <- data.frame(letters = letters, numbers = 1:26)
> word <- c("w", "o", "r", "d")
> w <-sapply(word[1], function(x) {
n <- alphabet[alphabet$letters == x,"numbers"]
df <- data.frame(letter = x, number = n)
return(df)
}, USE.NAMES = F)
# [,1]
# letter "w"
# number 23
The output is a length-2 list, even though df
should be a data frame.
I'd expect the output to be the same as calling data.frame()
outside of the anonymous function:
> data.frame(letter = "w", number = 23)
# letter number
# 1 w 23
Why is my sapply output not in the same form as when I call data.frame()
outside of sapply()
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论