Reading a csv file as matrix and change the entries using conditional if in R

Viewed 226

I have the csv file and I want to read it as a dataframe or matrix. I successfully read the .csv file, but when I want to change the entries based on conditional if statement, it does not work. The csv file can be downloaded here mydata

I want to read this .csv file as a matrix or dataframe. Then, I want to change the entries to "YES" or "NO" based on some condition. I tried this:

mydata = read.csv("mydata.csv")
mydata = data.frame(mydata)
ifelse(mydata>0.005, "YES", "NO")
mydata

However, the result I got are output1 and output2

I have tried this

mydata = 
read.csv("/home/hudamoh/scRNAspatial/binomial/tangram_output.csv")
myresult = data.frame(mydata)
myresult[myresult>0.0005] <- "YES"
myresult[myresult<=0.0005] <- "NO"
myresult

But the output I got is that some are not changed to "YES" or "NO". Also I want it looks like matrix where the rows should be 0, 1, 9. Please help.
myresult

2 Answers

In the second case, the logical matrix should be created before updating i.e.

i1 <- myresult>0.0005

Once we update to 'YES', its type changes to character and thus when we do the second time, it won't work. Also, it is better not to do the same step twice, instead do this once, store as an object and keep using it i.e. in the second case, we just need to negate (!) so that TRUE -> FALSE and FALSE -> TRUE

myresult[i1] <- "YES"
myresult[!i1] <- "NO"

In the first case with ifelse, the issue is that ifelse is applied on a logical 'matrix' as the 'test', and it returns a vector while stripping off the dim attributes. In order to preserve the dim attributes, we can use [] while assignment

mydata[] <- ifelse(mydata > 0.005, "YES", "NO")

Try this:

myresult <- as.data.frame(lapply(mydata, function(v) ifelse(v > 0.005, "YES", "NO")))

Note that here mydata is not an array but a dataframe, i.e. a list of vectors, with the data.frame class. The above applies the ifelse to each column.

Alternately, it's also possible to apply ifelse to the whole dataframe at once. However the result is not a dataframe but a matrix: the dataframe is first converted to matrix in order to be able to apply ifelse to the vector of all matrix elements, which you can't do directly with a dataframe. You can then convert the result back to a dataframe:

myresult <- as.data.frame(ifelse(mydata > 0.0005, "YES", "NO"))

Note that your dataframe has 3468 columns. The read.csv function assumes by default that the first row contains variable names. Since they are numbers, R prepends an X, hence thos strange Xnnnn appearing. If the first row contains data, pass an option:

read.csv("mydata.csv", header = F)

The variable names are then V1, V2... V3468.

Related