bluepill5
bluepill5

Reputation: 13

R - Read a file with a column who contains a string with commas

I trying to read a file that contains a column with a string with comma, somehting like this:

Input <- "A, B, C
1.76, 1%, yei, yei
2.00, 2%, foo
3.000, 3% , foo"

Where: yei, yei is the value of colum C:

A      B        C
1.76   1%   yei, yei
2.00   2%      test
3.000  3%      foo

I thought that maybe a conversion function works, is possible to deal with this case in R?

Upvotes: 1

Views: 61

Answers (2)

akrun
akrun

Reputation: 887118

We can use read.table

Input <- read.table(text="A, B, C
1.76, 1%, 'yei, yei'
2.00, 2%, foo
3.000, 3% , foo", sep=",", header=TRUE, stringsAsFactors=FALSE)

Input
#    A  B        C
#1 1.76 1% yei, yei
#2 2.00 2%      foo
#3 3.00 3%      foo

Update

If there are no quotes for 'yei, yei', we can create one with sub after reading with readLines

Input <- readLines(textConnection("A, B, C
1.76, 1%, yei, yei
2.00, 2%, foo
3.000, 3% , foo"))

 read.table(text=sub("(([^,]+,){2})\\s+(.*)", "\\1'\\3'", Input), 
             header=TRUE, sep=",", stringsAsFactors=FALSE)
 #     A    B        C
 #1 1.76   1% yei, yei
 #2 2.00   2%      foo
 #3 3.00  3%       foo

Upvotes: 2

milan
milan

Reputation: 4970

A <- c(1.76, 2.00, 3.000)
B <- c("1%", "2%", "3%")
C <- c("yei, yei", "foo", "foo")

as.data.frame(cbind(A,B,C))

#     A  B        C
#1 1.76 1% yei, yei
#2    2 2%      foo
#3    3 3%      foo

Upvotes: 1

Related Questions