如何用 R 中字符串列表中的值替换数据帧列表的行名?

发布于 2025-01-11 21:54:14 字数 577 浏览 3 评论 0原文

l为两个数据帧的列表,n为字符串列表,其中ln都有两个要素。另外,让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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

开始看清了 2025-01-18 21:54:14

您可以使用 rownames<-Map,如下所示

Map(`rownames<-`, l, n)
# or mapply(`rownames<-`, x = l, value = n, SIMPLIFY = FALSE)

结果

#[[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

rownames<-x 的 rowname 设置为 。在您的情况下,xl中的单个数据帧,value是来自n的向量。此函数应用于“每个...参数的第一个元素、第二个元素、第三个元素,依此类推。”,来自 ?mapply

并且“Mapmaply 的简单包装器,它不会尝试简化结果”,请参阅 ?Map

You can use rownames<- and Map as follows

Map(`rownames<-`, l, n)
# or mapply(`rownames<-`, x = l, value = n, SIMPLIFY = FALSE)

Result

#[[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

rownames<- sets the rownames of x to value. In your case x is a single dataframe in l, and value is a vector from n. 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 to mapply which does not attempt to simplify the result", see ?Map

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文