Home > other >  R does not recognize NA as missing data when I am importing a csv file
R does not recognize NA as missing data when I am importing a csv file

Time:02-10

In my first R script, I am creating a large dataset and exporting as a csv file.

In my second R script, I am importing by every SampleID to analyze the data.

The problem is that R is not recognizing NA as missing. How can I import the csv file into R so that my data are recognized as numeric?

Thank you.

### R Script One
SampleID <- c(1,1, 2,2, 3,3, 4,4)
x1 <- runif(8) * 10
x2 <- runif(8) * 10

my_df<- as.data.frame(cbind(SampleID, x1, x2))

my_df[2,3] <- NA
my_df[5,2] <- NA

write.csv(my_df, "my_df.csv", row.names = FALSE) #write out csv file from first R script


### R Script Two
library(sqldf)

j <- 3
select <- paste0("select * from file where SampleID=",j,"")
my_df2 <- read.csv.sql("my_df.csv", select) #Import only certain records into second R script


mode(my_df2$x1)

CodePudding user response:

After reading in the csv file, you can use readr::type_convert() to convert the column types.

library(read)

my_df2 <- read.csv.sql("./Downloads/my_df.csv", select) %>% readr::type_convert()

mode(my_df2$x1)
[1] "numeric"
  • Related