I'm not sure if this is possible in R, but I have a dataframe original_data
with one row and columns as follows:
A Ar A1 A1r B Br B1 B1r C Cr C1 C1r...... 0 0.1 0.5 0.1 0.1 0.6 0.7 1.2 1.4 1.2 1.5 1.8.....
structure(list(A = 0L, Ar = 0.1, A1 = 0.5, A1r = 0.1, B = 0.1,
Br = 0.6, B1 = 0.7, B1r = 1.2, C = 1.4, Cr = 1.2, C1 = 1.5,
C1r = 1.8), row.names = c(NA, -1L), class = "data.frame")
To explain what A, Ar, A1, and A1r
mean:
A
: ID with measurement taken at Visit 1.
Ar
: Same ID as A
but a replicate from Visit1
A1
: Same ID as A
, but measurement taken at Visit 2.
A1r
: Same ID as A
, but a replicate of the measurement A1
.
I want to transform it to a dataframe that looks as follows:
ID Visit Replicate Value
A 1 1 0
A 1 2 0.1
A 2 1 0.5
A 2 2 0.1
B 1 1 0.1
B 1 2 0.6
B 2 1 0.7
B 2 2 1.2
I tried to do it in R:
new_data_frame = data.frame(ID=character(0),Visit=integer(0),Replicate=integer(0),Value=integer(0))
for(i in 1:ncol(original_data))
{ #this is for the column "ID"
new_data_frame$ID[i]=colnames(original_data)[i]
#this is for the column "Replicate"
if(grepl("r",colnames(original_data)[i])==True)
{
new_data_frame$Replicate[i]=2
}
else
{
new_data_frame$Replicate[i]=1
}
#this is for the column "Visit"
if(grepl("1",colnames(original_data)[i])==True)
{
new_data_frame$Visit[i]=2
}
else
{
new_data_frame$Visit[i]=1
}
#this is for the column "Value"
new_data_frame$Value[i]=original_data[,i]
}
I get an error:
Error in `$<-.data.frame`(`*tmp*`, "ID", value = NA_integer_) :
replacement has 1 row, data has 0
How can I fix my code to make this work?