在 R 中引用行号 [英] Referencing Row Number in R

查看:85
本文介绍了在 R 中引用行号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何引用观察的行号?例如,如果您有一个名为data"的 data.frame 并且想要创建一个变量 data$rownumber 等于每个观察的行号,如果没有使用循环?

How do I reference the row number of an observation? For example, if you have a data.frame called "data" and want to create a variable data$rownumber equal to each observation's row number, how would you do it without using a loop?

推荐答案

当您创建 data.frame 时,这些默认情况下显示为 rownames.

These are present by default as rownames when you create a data.frame.

R> df = data.frame('a' = rnorm(10), 'b' = runif(10), 'c' = letters[1:10])
R> df
            a          b c
1   0.3336944 0.39746731 a
2  -0.2334404 0.12242856 b
3   1.4886706 0.07984085 c
4  -1.4853724 0.83163342 d
5   0.7291344 0.10981827 e
6   0.1786753 0.47401690 f
7  -0.9173701 0.73992239 g
8   0.7805941 0.91925413 h
9   0.2469860 0.87979229 i
10  1.2810961 0.53289335 j

并且您可以通过 rownames 命令访问它们.

and you can access them via the rownames command.

R> rownames(df)
 [1] "1"  "2"  "3"  "4"  "5"  "6"  "7"  "8"  "9"  "10"

如果您需要将它们作为数字,只需通过添加 as.numeric 将它们强制转换为数字,如 as.numeric(rownames(df)).

if you need them as numbers, simply coerce to numeric by adding as.numeric, as in as.numeric(rownames(df)).

您不需要添加它们,就好像您知道要查找的内容一样(例如 item df$c == 'i',您可以使用 which 命令:

You don't need to add them, as if you know what you are looking for (say item df$c == 'i', you can use the which command:

R> which(df$c =='i')
[1] 9

或者如果您不知道该列

R> which(df == 'i', arr.ind=T)
     row col
[1,]   9   3

您可以使用 df[9, 'c']df$c[9] 访问元素.

you may access the element using df[9, 'c'], or df$c[9].

如果你想添加它们,你可以使用 df$rownumber <- as.numeric(rownames(df)),尽管这可能不如 df$rownumber <- 1:nrow(df) 因为在某些情况下,您可能已分配给 rownames,因此它们将不再是默认索引号(which 命令将继续返回索引号,即使如果您确实分配给 rownames).

If you wanted to add them you could use df$rownumber <- as.numeric(rownames(df)), though this may be less robust than df$rownumber <- 1:nrow(df) as there are cases when you might have assigned to rownames so they will no longer be the default index numbers (the which command will continue to return index numbers even if you do assign to rownames).

这篇关于在 R 中引用行号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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