Good morning,
I have a problem with my cycle for.
My dataframe is:
Name_FD
Column_A Column_B Column_C Column_D Column_X
Element1 8808864430 88440000011863 Text1 *NA*
Element2 8808877431 88455000045863 Text2 *NA*
Element3 8808886677 88447800011865 Text3 *NA*
Element4 8808888830 88455000045867 Text4 *NA*
Element5 8808888830 88440000011869 Text5 *NA*
Element6 8808888830 88455000045810 Text6 *NA*
Element7 8808889977 88447800011865 Text3 *NA*
Element7 8808889977 88447800011865 Text3 *NA*
My code is:
Name_FD$Column_X <- rep(NA, length(Name_FD$Column_B))
for (i in Name_FD$Column_B){
for ( j in Name_FD$Column_B[-1,]) {
if(i == j) {
Fonte_Dati$x[i]= 1
} else {
Fonte_Dati$x[i]= 0
}
}
}
The errors are:
Error in Name_FD$Column_B[-1, ] : incorrect number of dimensions
Error in `$<-.data.frame`(`*tmp*`, "Column_X", value = c(NA, NA, NA, NA, NA, :
replacement has 16669 rows, data has 16668
The Column_B is ordered from the smallest to the largest.
I 'd like to know, for example, if the element of Colum_B [3,] is equal with the element of Column_B[4,].
If this is true, I'd like to insert 1 in the Column_X (in the same row of the element of Column_B[4,]) , otherwise 0.
Someone would be so kind to say me where I was wrong.
Thanks in advance.
Francesco
Name_FD <- read.table( text = "Column_A Column_B Column_C Column_D
Element1 8808864430 88440000011863 Text1
Element2 8808877431 88455000045863 Text2
Element3 8808886677 88447800011865 Text3
Element4 8808888830 88455000045867 Text4
Element5 8808888830 88440000011869 Text5
Element6 8808888830 88455000045810 Text6
Element7 8808889977 88447800011865 Text3
Element7 8808889977 88447800011865 Text3", header = TRUE)
library(tidyverse)
Name_FD %>% mutate( Column_X = ifelse( Column_B == lead( Column_B ), 1, 0 ) )
# Column_A Column_B Column_C Column_D Column_X
# 1 Element1 8808864430 8.84400e+13 Text1 0
# 2 Element2 8808877431 8.84550e+13 Text2 0
# 3 Element3 8808886677 8.84478e+13 Text3 0
# 4 Element4 8808888830 8.84550e+13 Text4 1
# 5 Element5 8808888830 8.84400e+13 Text5 1
# 6 Element6 8808888830 8.84550e+13 Text6 0
# 7 Element7 8808889977 8.84478e+13 Text3 1
# 8 Element7 8808889977 8.84478e+13 Text3 NA
I think there is a much simpler way of doing this :)
library(dplyr)
Name_FD %>%
mutate(Column_X = ifelse(Column_B == lead(Column_B), 1, 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.