Dataframe 如何在R中的另一个数据帧中获取要查找的值的行和列
我有两个s。其中一个如下所示:Dataframe 如何在R中的另一个数据帧中获取要查找的值的行和列,dataframe,r,for-loop,data-manipulation,Dataframe,R,For Loop,Data Manipulation,我有两个s。其中一个如下所示: 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 ... 现在我想让我的新
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 ...
我应该循环一下吗?如果是这样,如何获取要附加的行名称和列名并将其更改为数值?一个选项是转换为
矩阵
,然后使用melt
返回3列data.frame,然后根据第二个data.frame中的值对该data.frame进行子集
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
数据
df1我们可以获取长格式的第一个数据帧,然后进行连接
使用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
df1%>%
TIBLE::行名到列('latitude')%>%
tidyr::pivot_更长(cols=-纬度,值_至='海拔',
名称_to=‘经度’%%>%
dplyr::右联合(df2,by='elevation')
#经纬度高程
#
#1 36.5 113.5 1651
#2 33.5 113.5 549
另一个选项合并(melt(as.matrix(df1))、df2、by.x=“value”、by.y=“elevation”)
我的代码有什么问题?它显示仅使用基本R函数
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))
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