【问题标题】:Is there an R function to transform words in a cell to letters?是否有 R 函数可以将单元格中的单词转换为字母?
【发布时间】:2021-08-26 13:37:18
【问题描述】:

我的 DataFrame 看起来像这样

col1
"word1 word2 word3"
"word2 word3 word1"

我希望将单词序列转换为字母序列,例如

col1
"abc"
"bca"

非常感谢任何帮助!

【问题讨论】:

  • 需要更多信息。第一行是其余行的模板吗?它永远是 abc?

标签: string extract


【解决方案1】:

我没有使用过 R。使用下面的(JavaScript)作为伪代码来做你在 R 中需要的事情。 基于有限的数据。这就是我所拥有的。如果它没有帮助,它可能会提示您需要做什么。

Loopy Rewrite for Data:jsFiddle

  • 遍历数组

  • 比较元素

  • 根据默认行写出新值

      let data = [
          "word1 word2 word3",
          "word1 word3 word2",
          "word2 word3 word1",
          "word2 word1 word3",
          "word3 word2 word1",
          "word3 word1 word2"
      ];
    
      let newData = []
      let defaultRow;
      // act on each row to determine order
      data.forEach((row, index) => {
          // if first row it is our template for ordering
          if (index === 0) {
              defaultRow = row.split(' ');
              // can be more dynamic here about what is used and if more words in row
              newData.push("abc");
          } else {
              let result = '';
              // take your string and for each row and turn into an array
              row.split(' ').forEach((word) => {
                  let index = defaultRow.indexOf(word);
                  // assuming always three words this should work
                  if (index >= 0 && index < 3) {
                      // concatenate value to end of string
                      result += index === 0 ? 'a' : index === 1 ? 'b' : 'c';
                  } else {
                      console.log('bad data');
                  }
              })
              newData.push(result);
          }
      });
      alert(newData);
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-26
    • 2015-11-24
    • 2015-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多