Reputation: 191
i guess, there is as solution in the deep of www, but i can't found it. So I ask here with the hope that it will also help others.
I've a data.frame with multiple columns of the same type of columns. Some are empty some not.
a <- c(sku = "12345678", Image.1 = "name1.jpg", Image.2 = "name2.jpg", Image.3 = "", Image.4 = "name4.jpg", Image.5 = "", Image.6 = "", Image.5 = "name7.jpg")
sku Image.1 Image.2 Image.3 Image.4 Image.5 Image.6 Image.5
"12345678" "name1.jpg" "name2.jpg" "" "name4.jpg" "" "" "name7.jpg"
Now I want to move the column values to the left so that all empty columns are at the end of the line. Expacted result:
sku Image.1 Image.2 Image.3 Image.4 Image.5 Image.6 Image.5
"12345678" "name1.jpg" "name2.jpg" "name4.jpg" "name7.jpg" "" "" ""
Many thanks for your help
Upvotes: 0
Views: 139
Reputation: 388982
You can use order
:
a[] <- a[order(a == '')]
a
# sku Image.1 Image.2 Image.3 Image.4
# "12345678" "name1.jpg" "name2.jpg" "name4.jpg" "name7.jpg"
# Image.5 Image.6 Image.5
# "" "" ""
Upvotes: 1
Reputation: 39667
You can use nchar
to get the number of characters and then subset one using those with more than 0 and than those with 0 characters.
i <- nchar(a)==0
c(a[!i], a[i])
# sku Image.1 Image.2 Image.4 Image.5 Image.3 Image.5 Image.6
# "12345678" "name1.jpg" "name2.jpg" "name4.jpg" "name7.jpg" "" "" ""
In case the names should stay where they are use setNames
:
setNames(c(a[!i], a[i]), names(a))
# sku Image.1 Image.2 Image.3 Image.4 Image.5 Image.6 Image.5
# "12345678" "name1.jpg" "name2.jpg" "name4.jpg" "name7.jpg" "" "" ""
or overwrite the data of a
:
a[] <- c(a[!i], a[i])
# sku Image.1 Image.2 Image.3 Image.4 Image.5 Image.6 Image.5
# "12345678" "name1.jpg" "name2.jpg" "name4.jpg" "name7.jpg" "" "" ""
Upvotes: 2