按R中的行号合并 [英] Merge by row number in R

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

问题描述

我正在尝试合并两个数据帧dat1dat2.

I am trying to merge two data frames, dat1 and dat2.

dat1是n x 65数据帧,其rownames对应于dat2中的特定值.这是一个较小的玩具示例:

dat1 is an n x 65 data frame, whose rownames correspond to specific values in dat2. Here's a smaller, toy example:

 year <- c(1998, 2001, 2002, 2004, 2008)
 make <- c("Ford", "Dodge", "Toyota", "Tesla", "Jeep") 
 model <- c("Escape", "Ram", "Camry", "Model S", "Wrangler")
 price <- c(4750.00, 14567.00, 20000.00, 60123.00, 18469.00) 
 dat1 <- data.frame(year, make, model, price)

dat2是nx1向量,只有一个列称为rownumber.它包含来自dat1的感兴趣的行号.这是一个示例:

dat2 is an nx1 vector with a single column called rownumber. It contains row numbers from dat1 which are of interest. Here's an example:

dat2 <- as.data.frame(c(12, 45, 56, 123))
colnames(dat1)[1] <- "rownumber" 

我尝试如下合并两个数据帧:

I attempt to merge both data frames as follows:

dat3 <- merge(dat1, dat2, by = "row.names", all.x = TRUE, all.y = FALSE)

问题是dat3包含两个不匹配的列,row.namesrownumber.例如,在dat3的第一行中,row.names = 1,但rownumber =777.

The problem is that dat3 contains two columns, row.names and rownumber which do not match. For example, in row one of dat3, row.names = 1, but rownumber = 777.

关于如何解决此问题的任何想法?提前致谢.

Any thoughts on how to resolve this? Thanks in advance.

推荐答案

假设您有一个名为dat1data.frame对象,如下所示:

Say you have a data.frame object called dat1 as defined below:

> year <- c(1998, 2001, 2002, 2004, 2008)
> make <- c("Ford", "Dodge", "Toyota", "Tesla", "Jeep") 
> model <- c("Escape", "Ram", "Camry", "Model S", "Wrangler")
> price <- c(4750.00, 14567.00, 20000.00, 60123.00, 18469.00) 
> dat1 <- data.frame(year, make, model, price)

假设您有一个向量rownumbers,它定义了dat1中感兴趣的行.

Say you have a vector rownumbers that defines rows of interest from dat1.

> rownumbers <- c(2,5)

您的问题并没有说明期望的结果,但是假设您希望对dat1行进行子集处理,以使它们的行号位于向量rownumbers中,一种简单的方法是:

Your question does not state the desired results but assuming you want to subset rows of dat1 such that their row numbers are in the vector rownumbers, one simple way to do this is:

> dat1[rownumbers,] # Don't forget the comma
  year  make    model price
2 2001 Dodge      Ram 14567
5 2008  Jeep Wrangler 18469

您可以根据需要将子集分配给新变量dat3.

you can assign your subset to a new variable dat3 if you'd like.

> dat3 <- dat1[rownumbers,]

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

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