I have a csv file looking like this:
data[1,]"0;0;0;0";"0;0;0;0";"1395,387994;0;0;0";"1438,433382;0;0;0";"1477,891654;0;0;0";NA;NA;NA;NA
data[2,]"0;0;0;0";"1129,941435;0;0;0";"1140,702782;0;0;0";"1140,702782;0;0;0";"2415,922401;0;0;0";"2469,729136;0;0;0";"2545,058565;0;0;0";NA;NA
data[3,]"0;0;0;0";"0;0;0;0";"0;0;0;0";"0;0;0;0";"1506,58858;0;0;0";"1506,58858;0;0;0";"1517,349927;0;0;0";"1528,111274;0;0;0";NA
basically its 238 by 581 data frame. What I want is to keep NA's as NA's, to convert "0;0;0;0"'s into NA's and get the first number from objects where their is a non-zero value for the first position like "1506,58858;0;0;0".
result should look like this:
data[1,] NA NA 1395,387994 1438,433382 1140,702782 Na NA NA NA
data[2,] NA 1129,941435 1140,702782 1140,702782 2415,922401 2469,729136 2545,058565 NA NA
data[2,] NA NA NA NA 1506,58858 1506,58858 1517,349927 1528,111274 NA
I read my data like this:
f0=read.table("D:../f0.per.call.csv",sep=";",na.strings =c("NA","0;0;0;0"),stringsAsFactors = FALSE)
I know it is very easy task but I can't figure it out, I keep on getting errors when I am trying to convert characters to numerical values.. Any help will be appreciated, thanks.
I would do it in 2 steps, after I read the file:
Here is the code I used to replace the "0;0;0":
dat <- read.table("D:../f0.per.call.csv",
sep=";",na.strings =c("NA"),stringsAsFactors = FALSE)
dat[dat=="0;0;0;0"] <- NA
sapply(dat,function(x)gsub("(.*);0;0;0","\\1",x))
V1 V2 V3 V4 V5 V6 V7 V8 V9
[1,] NA NA "1395,387994" "1438,433382" "1477,891654" NA NA NA NA
[2,] NA "1129,941435" "1140,702782" "1140,702782" "2415,922401" "2469,729136" "2545,058565" NA NA
[3,] NA NA NA NA "1506,58858" "1506,58858" "1517,349927" "1528,111274" NA
After reading in your data, you can use strsplit
and extract just the first item using lapply
/ sapply
/ vapply
. Here's an example:
f0 <- read.table("D:../f0.per.call.csv", sep=";",
na.strings = c("NA","0;0;0;0"),
stringsAsFactors = FALSE)
f0[] <- lapply(f0, function(y)
vapply(strsplit(as.character(y), ";"),
function(z) z[[1]], ""))
f0
# V1 V2 V3 V4 V5 V6 V7 V8 V9
# 1 <NA> <NA> 1395,387994 1438,433382 1477,891654 <NA> <NA> <NA> <NA>
# 2 <NA> 1129,941435 1140,702782 1140,702782 2415,922401 2469,729136 2545,058565 <NA> <NA>
# 3 <NA> <NA> <NA> <NA> 1506,58858 1506,58858 1517,349927 1528,111274 <NA>
The result here is a data.frame
, just like the input was a data.frame
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.