如何从read.csv生成的数据帧而不是列表中获取单个值?

时间:2019-06-17 10:15:18

标签: r csv dataframe read.csv

我在数据路径上使用read.csv。它返回一个数据帧。我希望能够在此数据框中获得单个值,但我却获得了显示水平的值列表。

我尝试了几种方法来获取所需的值。在下一部分中,我将向您展示我的尝试和获得的结果。

这是我的简单数据框:

"OGM","Nutrient","data3"
"tomato","iron",0.03
"domestic cat","iron",0.02
"zebrafish","zing",0.02
"giraffe","nitrate", 0.09
"common cougar","manganese",0.05
"fawn","nitrogen",0.04
"daim","bromure",0.08
"wild cat","iron",0.05
"domestic cat","calcium",0.02
"muren","calcium",0.07
"jaguar","iron",0.02
"green turtle","sodium",0.01
"dave grohl","metal",0.09
"zebra","nitrates",0.12
"tortoise","sodium",0.16
"dinosaur","calcium",0.08
"apex mellifera","sodium",0.15

这是我加载数据的方式:

   #use read.csv on the datapath contained in file   
   fileData <- read.csv(file[4][[1]])
   print(fileData[1][1])

我想要的是访问一个值:例如,“ tomato”或“ nitrate”。我想要的结果就是这样:

>[1] tomato

这是我尝试过的,得到的结果:

print(fileData[1][1]) 返回

>  OGM
>1          tomato
>2    domestic cat
>3       zebrafish
>4         giraffe...

print(fileData$OGM[1]) 返回

>  [1] tomato
Levels: apex mellifera common cougar daim...

print(fileData[1][[1]]) 返回

> [1] tomato         domestic cat   zebrafish      giraffe        common cougar [...]       
[15] tortoise       dinosaur       apex mellifera
Levels: apex mellifera common cougar daim...

print(fileData$OGM[[1]]) 返回

Levels: apex mellifera common cougar daim...

为这个愚蠢的问题表示歉意,但我有点迷茫。感谢所有帮助。如果要我编辑帖子以使其更清晰,请告诉我。谢谢。

1 个答案:

答案 0 :(得分:1)

一些建议

尝试使用readr::read_csv而不是read.csv来读取数据。这将解决stringsAsFactors问题。或使用Stewart Macdonald建议的方法。

一旦有了数据,就可以按以下方式操作

# Make a sample dataframe

library(tidyverse)


df <- tribble(~OGM, ~Nutrient, ~data3,
"tomato","iron",0.03,
"domestic cat","iron",0.02,
"zebrafish","zing",0.02,
"giraffe","nitrate", 0.09,
"common cougar","manganese",0.05,
"fawn","nitrogen",0.04,
"daim","bromure",0.08,
"wild cat","iron",0.05,
"domestic cat","calcium",0.02,
"muren","calcium",0.07,
"jaguar","iron",0.02,
"green turtle","sodium",0.01,
"dave grohl","metal",0.09,
"zebra","nitrates",0.12,
"tortoise","sodium",0.16,
"dinosaur","calcium",0.08,
"apex mellifera","sodium",0.15)

df %>% 
  select(OGM) %>% # select the OGM column
  filter(OGM == 'tomato') %>% 
  pull # convert to a vector

[1] "tomato"