我有一个.csv文件:
ID; attribute1; attribute2; attribute3
1; 2; 3; 4
2; 7; 8; 3
3; 4; 6; 4
4; 2; 3; 4在一个单独的单词文档中,我有一个列表来解释每个值的含义。
属性1:
2你好
4再见
7例
当我读取并用r绘制数据时,如何查找每个属性的实际值(例如:“你好”、“再见”、“例子”)?而不是仅仅在情节上显示数字(例如"2“、"4”、"7")。
发布于 2018-04-26 23:03:45
您所需要做的就是将查找信息( Word文档中的内容)转换为dataframe,并将其与原始的dataframe合并。如果查找信息很小,比如在您的帖子中,您只需将其键入data.frame;否则,创建一个csv文件&将其读入R。
这里有两种方法,一种是使用来自dplyr的merge,另一种是使用基本R中的merge,它们都基于attribute1中的值连接数据。
编辑:@r2evans提出了一个很好的观点,即left_join更合适,因为它确保您不会因为它们有一个不包含在查找表中的属性而丢失观察结果。将两个示例更改为左联接。
library(tidyverse)
df <- "ID; attribute1; attribute2; attribute3
1; 2; 3; 4
2; 7; 8; 3
3; 4; 6; 4
4; 2; 3; 4" %>%
read_delim("; ", trim_ws = T)
lookup <- data.frame(
attribute1 = c(2, 4, 7),
attr1_text = c("Hello", "Goodbye", "Example")
)
left_join(df, lookup, by = "attribute1")
#> # A tibble: 4 x 5
#> ID attribute1 attribute2 attribute3 attr1_text
#> <int> <dbl> <int> <int> <fct>
#> 1 1 2. 3 4 Hello
#> 2 2 7. 8 3 Example
#> 3 3 4. 6 4 Goodbye
#> 4 4 2. 3 4 Hello
merge(df, lookup, by = "attribute1", all.x = T)
#> attribute1 ID attribute2 attribute3 attr1_text
#> 1 2 1 3 4 Hello
#> 2 2 4 3 4 Hello
#> 3 4 3 6 4 Goodbye
#> 4 7 2 8 3 Example由reprex封装创建于2018-04-26 (v0.2.0)。
https://stackoverflow.com/questions/50052845
复制相似问题