Am just new to R, just struggling to write a function to have a final table as shown in the final table. l have a data as seen below of two different fragments
chr start end gene1 chr start end gene2
chr1 2380 2370 0 chr1 3540 3589 0.03
chr2 4560 3458 0 chr2 4280 8790 0
chr2 4678 9846 1 chr2 4567 8648 1
chr2 4321 5679 0.04 chr2 4621 5678 0.002
I want to write a function that loops through the data, where its sees 0 in each row in gene1 and gene1 it should report 0 in finalgene but where there is a fraction either gene1 and gene2, it should report 1 in the corresponding column and where it sees 1 or fractions in either column it should report 1 as shown in the final file below
chr start end gene1 chr start end gene2 finalgene
chr1 2380 2370 0 chr1 3540 3589 0.03. 1
chr2 4560 3458 0 chr2 4280 8790 0 0
chr2 4678 9846 1 chr2 4567 8648 1 1
chr2 4321 5679 0.04 chr2 4621 5678 0.002 1
You can assign 1 if either gene1
or gene2
is not equal to 0 or 0 otherwise.
df$finalgene <- as.integer(df$gene1 != 0 | df$gene2 != 0)
Using ifelse
you can write the above as:
df$finalgene <- ifelse(df$gene1 != 0 | df$gene2 != 0, 1, 0)
We could also use rowSums
from base R
df$finalgene <- +(rowSums(df[c('gene1', 'gene2')] != 0) > 0)
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.