如何用 R 中字符串列表中的值替换数据帧列表的行名?
令l
为两个数据帧的列表,n
为字符串列表,其中l
和n
都有两个要素。另外,让l
中每个数据帧的行数等于n
中字符串向量的长度。
l <- list(data.frame(x = c(1,2,3), y = c(1,2,3)),
data.frame(x = c(1,2,3,4), y = c(1,2,3,4)))
n <- list(c('a', 'b', 'c'), c('a', 'b', 'c', 'd'))
假设我们要将l
中两个dataframe的rownames
替换为n
中的字符串。期望的结果是:
> l
[[1]]
x y
a 1 1
b 2 2
c 3 3
[[2]]
x y
a 1 1
b 2 2
c 3 3
d 4 4
我相信人们可以利用maply
来完成这项任务,但我不知道如何做到这一点。
Let l
be a list of two dataframes and n
a list of character strings, wherein l
and n
both have two elements. Also, let the number of rows of each dataframe in l
be equal to the length of the vector of character strings in n
.
l <- list(data.frame(x = c(1,2,3), y = c(1,2,3)),
data.frame(x = c(1,2,3,4), y = c(1,2,3,4)))
n <- list(c('a', 'b', 'c'), c('a', 'b', 'c', 'd'))
Suppose we want to replace the rownames
of the two dataframes in l
with the character strings in n
. The desired result would be:
> l
[[1]]
x y
a 1 1
b 2 2
c 3 3
[[2]]
x y
a 1 1
b 2 2
c 3 3
d 4 4
I believe one could exploit mapply
for this task, but I cannot figure how to do this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
rownames<-
和Map
,如下所示结果
rownames<-
将x
的 rowname 设置为值
。在您的情况下,x
是l
中的单个数据帧,value
是来自n
的向量。此函数应用于“每个...参数的第一个元素、第二个元素、第三个元素,依此类推。”,来自?mapply
。并且“
Map
是maply
的简单包装器,它不会尝试简化结果”,请参阅?Map
You can use
rownames<-
andMap
as followsResult
rownames<-
sets the rownames ofx
tovalue
. In your casex
is a single dataframe inl
, andvalue
is a vector fromn
. This function is applied "to the first elements of each ... argument, the second elements, the third elements, and so on.", from?mapply
.And "
Map
is a simple wrapper tomapply
which does not attempt to simplify the result", see?Map