我有两个数据帧。其中一个看起来如下:
114.5 113.5 112.5 111.5
36.5 1493 1651 1696 1918
35.5 1074 1336 1794 1891
33.5 358 549 609 815
另一个看起来像这样:
elevation
1 1651
2 549
3 ...
现在我想我的新数据帧是这样的:
elevation longitude Latitude
1 1651 113.5 36.5
2 549 113.5 33.5
3 ...
我应该循环浏览一下吗?如果是,如何以及如何将行名和列名附加并更改为数值?
一个选项是转换为matrix
,然后使用melt
返回3列数据帧,然后根据第二个数据帧中的值对该数据帧进行子集设置
library(reshape2)
out <- subset(melt(as.matrix(df1)), value %in% df2$elevation)[3:1]
names(out) <- c('elevation', 'longitude', 'Latitude')
out
# elevation longitude Latitude
#4 1651 113.5 36.5
#6 549 113.5 33.5
或者如果我们选择仅使用base R
out <- subset(as.data.frame.table(as.matrix(df1)), Freq %in% df2$elevation)[3:1]
names(out) <- c('elevation', 'longitude', 'Latitude')
数据
df1 <- structure(list(`114.5` = c(1493L, 1074L, 358L), `113.5` = c(1651L,
1336L, 549L), `112.5` = c(1696L, 1794L, 609L), `111.5` = c(1918L,
1891L, 815L)), class = "data.frame", row.names = c("36.5", "35.5",
"33.5"))
df2 <- structure(list(elevation = c(1651, 549)), class = "data.frame",
row.names = c(NA,
-2L))
我们可以获得长格式的第一个数据帧,然后进行连接。
使用tidyverse
函数,可以执行以下操作:
df1 %>%
tibble::rownames_to_column('latitude') %>%
tidyr::pivot_longer(cols = -latitude, values_to = 'elevation',
names_to = 'longitude') %>%
dplyr::right_join(df2, by = 'elevation')
# latitude longitude elevation
# <chr> <chr> <dbl>
#1 36.5 113.5 1651
#2 33.5 113.5 549