r if else for loop with logical and boollean operators - r

I'm trying to use an if else statement to create a new column of binary data in my data frame, but what I get is all zeros...
command:
for(i in 1:nrow(asort)){
if(asort$recip==0 && asort$dist<.74){
asort$temp[i]<-0
} else{
asort$temp[i]<-1
}
}
#temp ends up being all 0's
In addition, I would actually like to ask something along the lines of this:
# if the data in the recip column = 0, and the distances is < 0.74, OR if the #data is greater than 1.85 give me a zero, else 1
for(i in 1:nrow(asort)){
if(asort$recip==0 && asort$dist<.74 || asort$dist>1.85){
asort$temp[i]<-0
} else{
asort$temp[i]<-1
}
}
> head(asort)
coordinates CLASS_ID Flight UFID dist nnid nnid2 observed recip temp
157 (285293.3, 4426017) 0 F4_ F4_156 0.3857936 158 F4_157 0 0 0
158 (285293.2, 4426017) 0 F4_ F4_157 0.3857936 157 F4_156 0 0 0
259 (285255, 4426014) 0 F4_ F4_258 0.5226039 261 F4_260 1 0 0
261 (285255, 4426014) 0 F4_ F4_260 0.5226039 259 F4_258 1 0 0
402 (285275.3, 4426004) 0 F4_ F4_401 0.5598427 403 F4_402 1 0 0
403 (285275.6, 4426004) 0 F4_ F4_402 0.5598427 402 F4_401 1 0 0

Using df data.frame
dist <- runif(10, 0.3, 2)
recip<- c(0,1,1,0,1,0,1,0,0,1)
df <- data.frame(dist, recip)
and ifelse
df$temp<-ifelse(df$dist < 0.74 & df$recip == 0 , 0,
ifelse(df$dist > 1.85 & df$recip == 0, 0, 1))
> head(df)
# dist recip temp
#1 1.1878002 0 1
#2 0.4147835 1 1
#3 1.3707311 1 1
#4 0.9008034 0 1
#5 1.0220149 1 1
#6 1.9384069 0 0

Related

UpSetR error when using queries: replacement has 1 row, data has 0

I have tried to use UpsetR to visualize the input file which can be found here
> library("UpSetR")
> orthogroups_df<- read.table("orthogroups.GeneCount.tsv", header=T, stringsAsFactors = F)
> #All species
> selected_species <- colnames(orthogroups_df)[2:(ncol(orthogroups_df) -1)]
> selected_species
[1] "Atha" "Cann" "NQLD" "Natt" "Ngla" "Nlab" "Nsyl" "Ntab" "Ntom" "Slyc" "Stub" "Vvin"
> head(orthogroups_df)
Orthogroup Atha Cann NQLD Natt Ngla Nlab Nsyl Ntab Ntom Slyc Stub Vvin Total
1 OG0000000 0 0 965 0 0 3 0 0 0 0 0 0 968
2 OG0000001 0 1 3 0 0 448 0 0 0 0 0 0 452
3 OG0000002 0 1 313 0 0 120 1 0 1 0 0 0 436
4 OG0000003 0 93 15 21 46 16 33 63 36 25 39 26 413
5 OG0000004 1 42 2 34 109 6 8 154 11 9 4 0 380
6 OG0000005 0 2 61 1 34 44 91 70 43 20 1 0 367
> ncol(orthogroups_df)
[1] 14
> orthogroups_df[orthogroups_df > 0] <- 1
> upset(orthogroups_df,
+ nsets = ncol(orthogroups_df),
+ sets = rev(c(selected_species)),
+ queries = list(list(query = intersects, params = list("NQLD", "Nlab", "Nsyl"), color = "#238c45", active = T),
+ list(query = intersects, params = list("NQLD", "Nlab"), color = "#ffd977", active = T)))
Error in `$<-.data.frame`(`*tmp*`, "freq", value = 45L) :
replacement has 1 row, data has 0
How is it possible to fix the above error?
We need to set the number of intersects - nintersects - to a higher number so that sets in query params can be shown.
By default nintersects is set to 40, and list("NQLD", "Nlab", "Nsyl") appears after 40 at 90th position, so we need a bigger number, here I tried with 90:
upset(orthogroups_df,
nsets = ncol(orthogroups_df),
sets = rev(c(selected_species)),
nintersects = 90,
queries = list(
list(query = intersects,
params = list("NQLD", "Nlab", "Nsyl"),
color = "red",
active = TRUE),
list(query = intersects,
params = list("NQLD", "Nlab"),
color = "blue",
active = TRUE)))

How can I plot square wave data in R?

Consider the following data, where the left column represents a bit (1 or 0), and the right column represents the number of microseconds that we observe the bit.
0 664
1 63
0 404
1 544
0 651
1 686
0 507
1 1155
0 664
1 271
0 456
1 2763
0 664
1 115
0 456
1 4010
0 664
1 63
0 351
1 3855
I would like to plot this data such that there is a horizontal line at 0 with a width of 664, followed by a rise to a horizontal line at 1 with a width of 63, followed by a fall to a horizontal line at 0 with a width of 404, and so on.
Is there an efficient and direct way to plot this in R that does not involve manual comparison against bounds?
Here is my current code for doing this which is extremely inefficient and naive, so I hope there is a better way.
args <- commandArgs(trailingOnly = TRUE)
data = read.table(args[1])
current = 1
sumA = 0
pf = function(x) {
if (x < sumA) {
return(data[current,1])
}
for (i in current: length(data[,1])) {
sumA <<- sumA + data[i,2]
if (x < sumA) {
current <<- i + 1
return(data[i,1])
}
}
return("OUT OF BOUNDS")
}
cumSum = colSums(data)[[2]]
print(cumSum - 1);
h = Vectorize(pf)
plot(h, 1, cumSum-1, n=cumSum-1, lwd=0.001, xlim=c(0,cumSum-1))
As mentioned in my comment, plot command with type flag set to s should do the trick.
E.g., for you first 10 samples:
x <- c(0,664,63,404,544,651,686,507,1155,664,271)
xC <- cumsum(x)
y <- c(0,1,0,1,0,1,0,1,0,1,0)
plot(xC,y,type='s')

Creating a connection matrix from a data frame in R

I have some data in this form:
> agreers <- read.csv('agreers.csv')
> attach(agreers)
> head(agreers)
wain1 wain2 count
1 Founder36 Mnist10_269 673
2 Founder3 Mnist10_19 665
3 Mnist10_140 Mnist10_257 663
4 Founder1 Founder15 659
5 Founder21 Founder25 654
6 Founder15 Founder32 654
I created the data such that wain1 <= wain2, so each pair appears in the table only once. So this would be an undirected graph.
I want to create a connection matrix, like so:
Mnist10_269 Mnist10_19 Mnist10_257 . . .
Founder36 673 ? ?
Founder3 ? 665 ?
Mnist10_140 ? ? 663
. . .
where the ?'s will be zero if there isn't any data in agreers. So here's what I've tried:
> mat = matrix(0, nrow = length(unique(wain1)), ncol = length(unique(wain2)))
> rownames(mat) = unique(wain1)
> colnames(mat) = unique(wain2)
> for(i in as.integer(rownames(agreers))) mat[wain1[i], wain2[i]] = count[i]
It does something, i.e., mat gets updated with numbers, but the numbers aren't in the right place! For example, I would expect this to return 673.
> mat["Founder36","Mnist10_269"]
[1] 0
EDIT: Here's a bit more of the data file, to show the "duplicated levels in factors" problem. Note that Mnist10_140 appears twice in the first column, but with different values in the second column.
wain1,wain2,count
Founder36,Mnist10_269,673
Founder3,Mnist10_19,665
Mnist10_140,Mnist10_257,663
Founder1,Founder15,659
Founder21,Founder25,654
Founder15,Founder32,654
Mnist10_140,Mnist10_84,643
When processing just that subset of the data, I get warnings:
> agreers <- read.csv('temp.csv')
> connections <- xtabs(count ~ factor(wain1, levels = wain1) + factor(wain2, levels = wain2), agreers)
Warning message:
In `levels<-`(`*tmp*`, value = if (nl == nL) as.character(labels) else paste0(labels, :
duplicated levels in factors are deprecated
If you like base R you can use table
df <- read.table(header=TRUE, text=' wain1 wain2 count
Founder36 Mnist10_269 673
Founder3 Mnist10_19 665
Mnist10_140 Mnist10_257 663
Founder1 Founder15 659
Founder21 Founder25 654
Founder15 Founder32 654')
tab <- with(df,table(factor(wain1, levels=unique(wain1)),
factor(wain2, levels=unique(wain2))))
tab[which(tab == 1)] = df$count
tab
Mnist10_269 Mnist10_19 Mnist10_257 Founder15 Founder25 Founder32
Founder36 673 0 0 0 0 0
Founder3 0 665 0 0 0 0
Mnist10_140 0 0 663 0 0 0
Founder1 0 0 0 659 0 0
Founder21 0 0 0 0 654 0
Founder15 0 0 0 0 0 654
EDIT
As #DavidArenburg suggests, you can also use xtabs
xtabs(count ~ factor(wain1, levels = unique(wain1)) + factor(wain2, levels = unique(wain2)), df)
Have a look at the package reshape2
library(reshape2)
agreers <- read.table(header = TRUE, stringsAsFactors = FALSE, sep = ',', text = "wain1,wain2,count\nFounder36,Mnist10_269,673\nFounder3,Mnist10_19,665\nMnist10_140,Mnist10_257,663\nFounder1,Founder15,659\nFounder21,Founder25,654\nFounder15,Founder32,654\n")
conMat <- dcast(agreers, wain1 ~ wain2, fill = 0)
rownames(conMat) <- conMat$wain1
conMat$wain1 <- NULL
conMat["Founder36","Mnist10_269"]
That should solve the problem.
EDIT
This does not result in sorted data. Have a look at #cdeterman solution instead
Here is a variation of #cdeterman's approach (df from the same post)
do.call(table, lapply(df[1:2], function(x)
factor(x, levels=unique(x))))*df[,3]
# wain2
# wain1 Mnist10_269 Mnist10_19 Mnist10_257 Founder15 Founder25 Founder32
# Founder36 673 0 0 0 0 0
# Founder3 0 665 0 0 0 0
# Mnist10_140 0 0 663 0 0 0
# Founder1 0 0 0 659 0 0
# Founder21 0 0 0 0 654 0
# Founder15 0 0 0 0 0 654

Efficient (repeat) looping

I am trying to evaluate if a price, price(k), in a given row,(k), is equal to the one above, price(k-1). If it is I want to sum the volume from the prior and the price in question, volume(k)+volume(k+1), and then remove the row with the duplicate price, row k.
I have the following repeat loop which I am applying to a large dataset looking to delete repeated values.
k <- 1
repeat{
if( Prices$Price[ k + 1 ] == Prices$Price[ k ] ){
Prices$CumVolume[ k + 1 ] <- Prices$CumVolume[ k + 1 ] + Prices$CumVolume[ k ]
Prices <- Prices[ -k , ]
k <- k + 1
if( k > nrow( Prices ) ) break
}
}
The loop is very slow and I was wondering if there are ways to speed it up. Unfortunately I am relatively new to R and am having difficulty working out the best way to go about this.
Also is there a way in R to observe the iteration the loop is currently up too? i.e. have it displayed in the workspace on each iteration?
Example data:
Date Time Price CumVolume Ret MeanRet VolRet
26 01-JAN-2009 21:30:01.783 96.660 537 0 0 0
31 01-JAN-2009 21:30:58.041 96.650 78 0 0 0
33 01-JAN-2009 21:34:09.589 96.640 60 0 0 0
35 01-JAN-2009 21:34:10.879 96.640 40 0 0 0
37 01-JAN-2009 21:35:55.001 96.635 50 0 0 0
It appears you want something like this:
DF <- read.table(text=" Date Time Price CumVolume Ret MeanRet VolRet
26 01-JAN-2009 21:30:01.783 96.660 537 0 0 0
31 01-JAN-2009 21:30:58.041 96.650 78 0 0 0
33 01-JAN-2009 21:34:09.589 96.640 60 0 0 0
35 01-JAN-2009 21:34:10.879 96.640 40 0 0 0
37 01-JAN-2009 21:35:55.001 96.635 50 0 0 0", header=TRUE)
#create a run id
DF$runs <- cumsum(c(TRUE, diff(DF$Price) != 0))
#sum per each price run
DF$CCVolume <- with(DF, ave(CumVolume, runs, FUN=sum))
#remove duplicated prices
DF[!duplicated(DF$Price), ]
# Date Time Price CumVolume Ret MeanRet VolRet runs CCVolume
#26 01-JAN-2009 21:30:01.783 96.660 537 0 0 0 1 537
#31 01-JAN-2009 21:30:58.041 96.650 78 0 0 0 2 78
#33 01-JAN-2009 21:34:09.589 96.640 60 0 0 0 3 100
#37 01-JAN-2009 21:35:55.001 96.635 50 0 0 0 4 50
I think your code is going in infinite loop because of your increment index.K=k+1 and Break is always within the condition,I hope you want this
k=1
z=unique(Prices$Price)
for(i in 1:length(z))
{
dupindex=which(z[i]==Prices$Price)
Prices$CumVolume[tail(dupindex,n=1)]=sum(Prices$CumVolume[dupindex])
Prices=Prices[-(dupindex[1:length(dupindex)-1]),]
}
I hope it help,thanks.

mistake in multivePenal but not in frailtyPenal

The libraries used are: library(survival)
library(splines)
library(boot)
library(frailtypack) and the function used is in the library frailty pack.
In my data I have two recurrent events(delta.stable and delta.unstable) and one terminal event (delta.censor). There are some time-varying explanatory variables, like unemployment rate(u.rate) (is quarterly) that's why my dataset has been splitted by quarters.
Here there is a link to the subsample used in the code just below, just in case it may be helpful to see the mistake. https://www.dropbox.com/s/spfywobydr94bml/cr_05_males_services.rda
The problem is that it takes a lot of time running until the warning message appear.
Main variables of the Survival function are:
I have two recurrent events:
delta.unstable (unst.): takes value one when the individual find an unstable job.
delta.stable (stable): takes value one when the individual find a stable job.
And one terminal event
delta.censor (d.censor): takes value one when the individual has death, retired or emigrated.
row id contadorbis unst. stable d.censor .t0 .t
1 78 1 0 1 0 0 88
2 101 2 0 1 0 0 46
3 155 3 0 1 0 0 27
4 170 4 0 0 0 0 61
5 170 4 1 0 0 61 86
6 213 5 0 0 0 0 92
7 213 5 0 0 0 92 182
8 213 5 0 0 0 182 273
9 213 5 0 0 0 273 365
10 213 5 1 0 0 365 394
11 334 6 0 1 0 0 6
12 334 7 1 0 0 0 38
13 369 8 0 0 0 0 27
14 369 8 0 0 0 27 119
15 369 8 0 0 0 119 209
16 369 8 0 0 0 209 300
17 369 8 0 0 0 300 392
When I apply multivePenal I obtain the following message:
Error en aggregate.data.frame(as.data.frame(x), ...) :
arguments must have same length
Además: Mensajes de aviso perdidos
In Surv(.t0, .t, delta.stable) : Stop time must be > start time, NA created
#### multivePenal function
fit.joint.05_malesP<multivePenal(Surv(.t0,.t,delta.stable)~cluster(contadorbis)+terminal(as.factor(delta.censor))+event2(delta.unstable),formula.terminalEvent=~1, formula2=~as.factor(h.skill),data=cr_05_males_serv,Frailty=TRUE,recurrentAG=TRUE,cross.validation=F,n.knots=c(7,7,7), kappa=c(1,1,1), maxit=1000, hazard="Splines")
I have checked if Surv(.t0,.t,delta.stable) contains NA, and there are no NA's.
In addition, when I apply for the same data the function frailtyPenal for both possible combinations, the function run well and I get results. I take one week looking at this and I do not find the key. I would appreciate some of light to this problem.
#delta unstable+death
enter code here
fit.joint.05_males<-frailtyPenal(Surv(.t0,.t,delta.unstable)~cluster(id)+u.rate+as.factor(h.skill)+as.factor(m.skill)+as.factor(non.manual)+as.factor(municipio)+as.factor(spanish.speakers)+ as.factor(no.spanish.speaker)+as.factor(Aged.16.19)+as.factor(Aged.20.24)+as.factor(Aged.25.29)+as.factor(Aged.30.34)+as.factor(Aged.35.39)+ as.factor(Aged.40.44)+as.factor(Aged.45.51)+as.factor(older61)+ as.factor(responsabilities)+
terminal(delta.censor),formula.terminalEvent=~u.rate+as.factor(h.skill)+as.factor(m.skill)+as.factor(municipio)+as.factor(spanish.speakers)+as.factor(no.spanish.speaker)+as.factor(Aged.16.19)+as.factor(Aged.20.24)+as.factor(Aged.25.29)+as.factor(Aged.30.34)+as.factor(Aged.35.39)+as.factor(Aged.40.44)+as.factor(Aged.45.51)+as.factor(older61)+ as.factor(responsabilities),data=cr_05_males_services,n.knots=12,kappa1=1000,kappa2=1000,maxit=1000, Frailty=TRUE,joint=TRUE, recurrentAG=TRUE)
###Be patient. The program is computing ...
###The program took 2259.42 seconds
#delta stable+death
fit.joint.05_males<frailtyPenal(Surv(.t0,.t,delta.stable)~cluster(id)+u.rate+as.factor(h.skill)+as.factor(m.skill)+as.factor(non.manual)+as.factor(municipio)+as.factor(spanish.speakers)+as.factor(no.spanish.speaker)+as.factor(Aged.16.19)+as.factor(Aged.20.24)+as.factor(Aged.25.29)+as.factor(Aged.30.34)+as.factor(Aged.35.39)+as.factor(Aged.40.44)+as.factor(Aged.45.51)+as.factor(older61)+as.factor(responsabilities)+terminal(delta.censor),formula.terminalEvent=~u.rate+as.factor(h.skill)+as.factor(m.skill)+as.factor(municipio)+as.factor(spanish.speakers)+as.factor(no.spanish.speaker)+as.factor(Aged.16.19)+as.factor(Aged.20.24)+as.factor(Aged.25.29)+as.factor(Aged.30.34)+as.factor(Aged.35.39)+as.factor(Aged.40.44)+as.factor(Aged.45.51)+as.factor(older61)+as.factor(responsabilities),data=cr_05_males_services,n.knots=12,kappa1=1000,kappa2=1000,maxit=1000, Frailty=TRUE,joint=TRUE, recurrentAG=TRUE)
###The program took 3167.15 seconds
Because you neither provide information about the packages used, nor the data necessary to run multivepenal or frailtyPenal, I can only help you with the Surv part (because I happened to have that package loaded).
The Surv warning message you provided (In Surv(.t0, .t, delta.stable) : Stop time must be > start time, NA created) suggests that something is strange with your variables .t0 (the time argument in Surv, refered to as 'start time' in the warning), and/or .t (time2 argument, 'Stop time' in the warning). I check this possibility with a simple example
# read the data you feed `Surv` with
df <- read.table(text = "row id contadorbis unst. stable d.censor .t0 .t
1 78 1 0 1 0 0 88
2 101 2 0 1 0 0 46
3 155 3 0 1 0 0 27
4 170 4 0 0 0 0 61
5 170 4 1 0 0 61 86
6 213 5 0 0 0 0 92
7 213 5 0 0 0 92 182
8 213 5 0 0 0 182 273
9 213 5 0 0 0 273 365
10 213 5 1 0 0 365 394
11 334 6 0 1 0 0 6
12 334 7 1 0 0 0 38
13 369 8 0 0 0 0 27
14 369 8 0 0 0 27 119
15 369 8 0 0 0 119 209
16 369 8 0 0 0 209 300
17 369 8 0 0 0 300 392", header = TRUE)
# create survival object
mysurv <- with(df, Surv(time = .t0, time2 = .t, event = stable))
mysurv
# create a new data set where one .t for some reason is less than .to
# on row five .t0 is 61, so I set .t to 60
df2 <- df
df2$.t[df2$.t == 86] <- 60
# create survival object using new data which contains at least one Stop time that is less than Start time
mysurv2 <- with(df2, Surv(time = .t0, time2 = .t, event = stable))
# Warning message:
# In Surv(time = .t0, time2 = .t, event = stable) :
# Stop time must be > start time, NA created
# i.e. the same warning message as you got
# check the survival object
mysurv2
# as you can see, the fifth interval contains NA
# I would recommend you check .t0 and .t in your data set carefully
# one way to examine rows where Stop time (.t) is less than start time (.t0) is:
df2[which(df2$.t0 > df2$.t), ]
I am not familiar with multivepenal but it seems that it does not accept a survival object which contains intervals with NA, whereas might frailtyPenal might do so.
The authors of the package have told me that the function is not finished yet, so perhaps that is the reason that it is not working well.
I encountered the same error and arrived at this solution.
frailtyPenal() will not accept data.frames of different length. The data.frame used in Surv and data.frame named in data= in frailtyPenal must be the same length. I used a Cox regression to identify the incomplete cases, reset the survival object to exclude the missing cases and, finally, run frailtyPenal:
library(survival)
library(frailtypack)
data(readmission)
#Reproduce the error
#change the first start time to NA
readmission[1,3] <- NA
#create a survival object with one missing time
surv.obj1 <- with(readmission, Surv(t.start, t.stop, event))
#observe the error
frailtyPenal(surv.obj1 ~ cluster(id) + dukes,
data=readmission,
cross.validation=FALSE,
n.knots=10,
kappa=1,
hazard="Splines")
#repair by resetting the surv object to omit the missing value(s)
#identify NAs using a Cox model
cox.na <- coxph(surv.obj1 ~ dukes, data = readmission)
#remove the NA cases from the original set to create complete cases
readmission2 <- readmission[-cox.na$na.action,]
#reset the survival object using the complete cases
surv.obj2 <- with(readmission2, Surv(t.start, t.stop, event))
#run frailtyPenal using the complete cases dataset and the complete cases Surv object
frailtyPenal(surv.obj2 ~ cluster(id) + dukes,
data = readmission2,
cross.validation = FALSE,
n.knots = 10,
kappa = 1,
hazard = "Splines")

Resources