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
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" "" "" ""
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
# "" "" ""
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.