在R中使用apply时如何打印当前行的名称? [英] How to print the name of current row when using apply in R?

查看:36
本文介绍了在R中使用apply时如何打印当前行的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有一个矩阵 k

> k
  d e
a 1 3
b 2 4

我想在 k 上应用一个函数

I want to apply a function on k

> apply(k,MARGIN=1,function(p) {p+1})
a b
d 2 3
e 4 5

但是,我还想打印 apply 所在行的 rowname,以便我可以知道当时应用了该函数的哪一行.

However, I also want to print the rowname of the row being apply so that I can know which row the function is applied on at that time.

它可能看起来像这样:

apply(k,MARGIN=1,function(p) {print(rowname(p)); p+1})

但我真的不知道如何在 R 中做到这一点.有人知道吗?

But I really don't do how to do that in R. Does anyone has any idea?

推荐答案

据我所知你不能用 apply 做到这一点,但你可以遍历 rownames你的数据框.蹩脚的例子:

As far as I know you cannot do that with apply, but you could loop through the rownames of your data frame. Lame example:

lapply(rownames(mtcars), function(x) sprintf('The mpg of %s is %s.', x, mtcars[x, 1]))

这篇关于在R中使用apply时如何打印当前行的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆