I created two data frame. One is blank to insert value from the other data frame. However, it doesn't insert the right value, it instead inserted some random numbers. Please advise.
this is my code:
name <- c(54,000,00)
age <- c(5, 3, 1)
weight <- c(120, 23, 245)
address <- c("kg", "kgi", "gg")
df1 <- data frame of name, age, weight, and address.
df2 <- # created 4 columns and 0 rows.
colnames(df2)[1] <- "Name"
colnames(df2)[2] <- "age"
colnames(df2)[3] <- "weight"
colnames(df2)[4] <- "address"
for (i in 1: ncol(df2)){
hd1 = colnames(df2)[i]
j <- 1
while (j <= ncol(df1)){
hd2 = colnames(df1)[j]
if(hd1 == hd2){
x <- 1
while(x <= nrow(df1)) {
df2[x,hd1] <- df1[x,colnames(df1)[j]]
x = x + 1
}
}
j = j + 1
}
}
the result of df2 is:
Where does the 2, 3, 1 come from in the address column.
Name age weight address
NA 5 120 2
NA 3 23 3
NA 1 245 1
As of now, we can't replay your code are there are missing pieces.
Could you please turn this into a self-contained reprex (short for reproducible example)? It will help us help you if we can be sure we're all working with/looking at the same stuff.
If you run into problems with access to your clipboard, you can specify an outfile for the reprex, and then copy and paste the contents into the forum.
name <- c(54,000,00)
age <- c(5, 3, 1)
weight <- c(120, 23, 245)
address <- c("kg", "kgi", "gg")
df1 <- data.frame(name, age, weight, address)
df2 <- data.frame(matrix(ncol = 4, nrow=0))
colnames(df2)[1] <- "Name"
colnames(df2)[2] <- "age"
colnames(df2)[3] <- "weight"
colnames(df2)[4] <- "address"
for (i in 1: ncol(df2)){
hd1 = colnames(df2)[i]
j <- 1
while (j <= ncol(df1)){
hd2 = colnames(df1)[j]
if(hd1 == hd2){
x <- 1
while(x <= nrow(df1)) {
df2[x,hd1] <- df1[x,colnames(df1)[j]]
x = x + 1
}
}
j = j + 1
}
}
Created on 2018-11-03 by the reprex package (v0.2.1)
Alright here is the reprex that I created. Hope this helps ! Can someone advise me why the result for address is number rather than text ?
If your question's been answered (even by you!), would you mind choosing a solution? It helps other people see which questions still need help, or find solutions if they have similar problems. Here’s how to do it: