首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >查找属性值R

查找属性值R
EN

Stack Overflow用户
提问于 2018-04-26 22:41:55
回答 1查看 82关注 0票数 0

我有一个.csv文件:

代码语言:javascript
复制
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")。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-04-26 23:03:45

您所需要做的就是将查找信息( Word文档中的内容)转换为dataframe,并将其与原始的dataframe合并。如果查找信息很小,比如在您的帖子中,您只需将其键入data.frame;否则,创建一个csv文件&将其读入R。

这里有两种方法,一种是使用来自dplyrmerge,另一种是使用基本R中的merge,它们都基于attribute1中的值连接数据。

编辑:@r2evans提出了一个很好的观点,即left_join更合适,因为它确保您不会因为它们有一个不包含在查找表中的属性而丢失观察结果。将两个示例更改为左联接。

代码语言:javascript
复制
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)。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50052845

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档